gpt4 book ai didi

javascript - 从 HTMLCollection 获取数组的 div

转载 作者:行者123 更新时间:2023-12-02 18:01:46 26 4
gpt4 key购买 nike

我只想返回每个 div 的 id 并将它们保存在一个数组中:

const projects = [...document.getElementsByClassName("nav-project")];
console.log(projects);

//expected output : [one, two, three, four, five]
<div class="nav-project" id="one">a</div>
<div class="nav-project" id="two">b</div>
<div class="nav-project" id="three">c</div>
<div class="nav-project" id="four">d</div>
<div class="nav-project" id="five">e</div>

最佳答案

尝试map :

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

const projects = [...document.getElementsByClassName("nav-project")]
.map(div => div.id);

console.log(projects);
<div class="nav-project" id="one">a</div>
<div class="nav-project" id="two">b</div>
<div class="nav-project" id="three">c</div>
<div class="nav-project" id="four">d</div>
<div class="nav-project" id="five">e</div>

关于javascript - 从 HTMLCollection 获取数组的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74228265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com