使用JavaScript将HTMLCollection转换为数组

4
我希望获取所有类名为“Box”的HTML元素,然后将该集合转换为数组,以便我可以通过位置访问每个元素。
这是我编写的代码:
function BoxAppearence() {
    
    var BoxCollection = document.getElementsByClassName("Box");
    console.log(BoxCollection)
    var Box = BoxCollection.split("");
    console.log(Box)
    
    console.log(Box[12])
}

BoxAppearence();

1
var BoxCollection = Array.from(document.getElementsByClassName("Box"));应该可以满足你的需求。 - secan
这是我的代码:function BoxAppearence() { var Box = Array.from(document.getElementsByClassName("Box")); console.log(Box); console.log(Box[12]); } BoxAppearence();但在控制台中显示的是:[] 和 undefined - WebDev001
请参考这个JSFiddle代码段,它是可行的;你确定提供了正确的类名吗(记住JavaScript区分大小写,“Box”和“box”不一样)?你确定你的页面包含了带有“Box”类的元素吗?你确定你在DOM完全加载后才执行该函数吗? - secan
这个回答解决了你的问题吗?将HTMLCollection转换为数组的最高效方法 - kmoser
1个回答

16

如评论中所提到的,您可以使用Array.from()将HTML集合转换为数组。

无论如何,如果您仅将集合转换为数组的原因是为了能够通过其索引/位置访问元素,则如下面的代码片段所示,您还可以使用HTML集合(但实际上您将使用对象“键”而不是索引)。

function BoxAppearence() {
  var BoxCollection = document.getElementsByClassName("Box");
  var BoxArray = Array.from(BoxCollection);
  
  console.log("### BoxCollection ###");
  console.log("Is 'BoxCollection' an array?", Array.isArray(BoxCollection));
  console.log(BoxCollection);
  console.log(BoxCollection[12])
  console.log('\n\n');
  console.log("### BoxArray ###");
  console.log("Is 'BoxArray' an array?", Array.isArray(BoxArray));
  console.log(BoxArray);
  console.log(BoxArray[12]);
}

BoxAppearence();
<div class="Box">box1</div>
<div class="Box">box2</div>
<div class="Box">box3</div>
<div class="Box">box4</div>
<div class="Box">box5</div>
<div class="Box">box6</div>
<div class="Box">box7</div>
<div class="Box">box8</div>
<div class="Box">box9</div>
<div class="Box">box10</div>
<div class="Box">box11</div>
<div class="Box">box12</div>
<div class="Box">box13</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接