【问题标题】:Convert HTMLCollection to an array with JavaScript使用 JavaScript 将 HTMLCollection 转换为数组
【发布时间】:2021-09-19 02:03:21
【问题描述】:

我想获取所有带有“Box”类的 HTML 元素,然后该集合将其转换为数组,这样我就可以通过位置访问每个元素。

这是我编写的代码:

function BoxAppearence() {
    
    var BoxCollection = document.getElementsByClassName("Box");
    console.log(BoxCollection)
    var Box = BoxCollection.split("");
    console.log(Box)
    
    console.log(Box[12])
}

BoxAppearence();

【问题讨论】:

  • var BoxCollection = Array.from(document.getElementsByClassName("Box")); 应该做你想做的事
  • 这是我的代码 rn: ``` function BoxAppearence() { var Box = Array.from(document.getElementsByClassName("Box"));控制台.log(框); console.log(Box[12]); } BoxAppearence(); ``` 但在控制台中显示:[] 和未定义
  • 正如您在JSFiddle snippet 中看到的那样,它有效;你确定你提供了正确的类名(记住 JavaScript 是区分大小写的,“Box”与“box”不同)?您确定您的页面包含带有“框”class 的元素吗?您确定要在 DOM 完全加载后执行函数吗?

标签: javascript arrays class classname htmlcollection


【解决方案1】:

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

无论如何,如果您将集合转换为数组的唯一原因是能够通过其索引/位置访问元素,正如您从下面的代码 sn-p 中看到的那样,您也可以使用 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    相关资源
    最近更新 更多