【问题标题】:How to dynamically add a class to an HTMLCollection (problem converting HTMLCollection into an array)?如何动态地将类添加到 HTMLCollection(将 HTMLCollection 转换为数组的问题)?
【发布时间】:2019-04-11 19:08:10
【问题描述】:
content = document.getElementsByClassName('outercontent'); 

生成目标 div 元素的 HTMLCollection。

我正在尝试将数组admin1中的每个索引处的字符串添加到每个索引处每个div的classList。

for(var i = 0; i < content.length; i++) {
  content[i].classList.add(admin1[i]);
}

当我现在 console.log content 时,我可以看到添加的新类 - 但是它只显示所有 div 的 admin1 数组中的第一个字符串。

我了解到您不能在 HTMLCollections 上使用 for 循环,因此我尝试在此处将 content 转换为数组:

var contentarr = [...content];

但是当我 console.log contentarr 时,我看到它的长度只有 1(索引 0)。

(这可能与这些 div 中只有一个最初存在于 html 中的事实有关,直到它被乘以 ng-repeat (angularjs)?)

那么如何将 HTMLCollection 转换为数组,然后从 admin1 数组中添加类?

谢谢。

编辑

更多上下文-

var subdivs2 = [];
var subdivs2 = angular.element(document.querySelector('[ng- 
controller="mainCtrl"]')).scope().subdivisions2

for(var i = 0; i < subdivs2.length; i++) {
  subdivs2[i] = subdivs2[i]["province"];
}

var admin1 = [];
for(var i = 0; i < subdivs2.length; i++) {
  admin1[i] = subdivs2[i][0]["name"];
}

我的角度控制器中有一个嵌套数组,名为subdivisions2。我将名为“name”的键的所有值放入admin1 数组中。

admin1 如下所示:

0: "Adrar"
1: "Algiers"
2: "Annaba"
3: "Aïn Defla"
4: "Aïn Témouchent"
5: "Batna"
6: "Biskra"
7: "Blida"
8: "Bordj Bou Arréridj"
9: "Boumerdès"
10: "Bouïra"
11: "Béchar"
12: "Béjaïa"
13: "Chlef"
14: "Constantine"
15: "Djelfa"
16: "El Bayadh"
17: "El Oued"
18: "El Taref"
19: "Ghardaïa"
20: "Illizi"
21: "Jijel"
22: "Khenchela"
23: "Laghouat"
24: "M'Sila"
25: "Mascara"
26: "Mila"
27: "Mostaganem"
28: "Médéa"
29: "Naâma"
30: "Oran"
31: "Ouargla"
32: "Oum el-Bouaghi"
33: "Relizane"
34: "Saïda"
35: "Sidi Bel Abbès"
36: "Skikda"
37: "Souk Ahras"
38: "Sétif"
39: "Tamanghasset"
40: "Tiaret"
41: "Tindouf"
42: "Tipaza"
43: "Tissemsilt"
44: "Tizi Ouzou"
45: "Tlemcen"
46: "Tébessa"

有趣的是,当我查看 HTMLCollection 时,它在底部显示“长度:47”(与 admin1 的长度相同)。但是当我把 console.log(content.length);上面写着 1. 为什么会这样?

【问题讨论】:

    标签: javascript html arrays for-loop htmlcollection


    【解决方案1】:

    问题是您只有一个循环,并且该循环可以很好地迭代 HTML 元素,但是当它遍历每个(仅一次)时,它只会添加样式当前循环索引。

    这里需要两个循环,一个用于遍历元素,另一个用于遍历样式,同时仍在元素上。

    这是一个例子:

    let classes = ["big","bold","blue"];
    
    // First, get all the elements you'll want to work with.
    // Don't use .getElementsByClassName! Use .querySelectorAll()
    let els = document.querySelectorAll(".special");
    
    // You can use regular counting loops on HTMLCollections, but
    // Arrays offer more robust looping without you having to manage 
    // indexes. So, we'll convert the collection to an array:
    els = Array.prototype.slice.call(els);
    
    // Loop over the elements array
    els.forEach(function(el){
       
       // Now, while we are on just one of the elements,
       // start a second loop to go over the string array
       classes.forEach(function(cls){
          // Add the class to the element that we're currently looping over
          el.classList.add(cls);
       });
    
    });
    .big { font-size:2em; }
    .bold { font-weight:bold; }
    .blue { color:blue; }
    <div class="special">Some Content</div>
    <p>Some Content</p>
    <div>Some Content</div>
    <p class="special">Some Content</p>
    <div class="special">Some Content</div>
    <p>Some Content</p>
    <div>Some Content</div>
    <p>Some Content</p>

    注意:Don't use .getElementsByClassName()!

    【讨论】:

    • 这一半有效!唯一的问题是我的“内容”数组(或您的示例中的“els”)的长度仅为 1,这意味着所有 47 个类都被添加到索引 0 处的一项。因为我使用的是 angular 的 ng-repeat也许我需要使用 setTimeout 来确保在加载所有 div 后发生这种情况
    • 感谢您的回答。我解决了它 - 问题是我需要使用延迟来等待 div 成倍增加。我原来的 for 循环完成了这项工作(为每个 div 添加一个唯一的类)。
    猜你喜欢
    • 1970-01-01
    • 2021-09-19
    • 2010-09-18
    • 2021-09-06
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多