在循环结构中将元素追加到DOM [英] Appending elements to DOM in a loop structure

查看:156
本文介绍了在循环结构中将元素追加到DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

页面加载完成后,我想为页面上的每个现有元素添加一个附加元素。

Once the page has been loaded, I would like to append an additional element for each existing elements on the page.

我尝试过类似的操作:

    var divs=document.getElementsByTagName('div');

    for(i=0;i<divs.length;i++){
        newDiv=document.createElement('div');
        divs[i].appendChild(newDiv);
    }

只是警告,它实际上会冻结浏览器因为divs变量是动态的,并且每次循环执行时divs.length都会变得越来越大。

Just a warning this will actually freezes the browser because the divs variable is dynamic and divs.length just gets larger and larger each time the loop goes.

有没有一种方法可以确定DOM是通常是第一次加载,并且有机会静态地使用元素。

Is there a way to determine the number of tags when the DOM is normally loaded for the first time and have a chance to work with the elements statically.

到目前为止,我还没有其他解决方案。

I can't there of another solution so far.

非常感谢。
丹尼斯!

Thanks so much. Dennis!

推荐答案

问题是DOM集合是 实时 ,并且当基础文档结构发生更改时,它将自动反映在集合上,即为什么当访问 length 属性时将包含新的长度,一种常见的方法是在开始循环之前 cache 长度:

The problem is that DOM collections are live, and when the underlying document structure is changed, it will be reflected automatically on the collection, that's why when the length property is accessed it will contain a new length, a common approach is to cache the length before starting the loop:

var divs=document.getElementsByTagName('div');

for(var i = 0, len = divs.length;i<len;i++){
    var newDiv = document.createElement('div');
    divs[i].appendChild(newDiv);
}

也请注意,您应使用<$声明所有变量c $ c> var 语句,否则它可能成为全局语句。

Also notice that you should declare all your variables with the var statement, otherwise it might become global.

编辑:在这种情况下,由于您要追加相同tagName的子节点,因此将修改集合,并且索引将不再匹配,在第一次迭代之后,索引 1 将引用上一个迭代中的 newDiv 对象,如 @ Casey 建议在遍历集合之前将其转换为纯数组会更安全。

In this case, since you are appending child nodes of the same tagName, the collection will be modified, and the indexes will no longer match, after the first iteration, the index 1 will refer to the newDiv object from the previous iteration, as @Casey recommends it will be safer to convert the collection to a plain array before traversing it.

我使用以下函数:

function toArray(obj) {
  var array = [];
  // iterate backwards ensuring that length is an UInt32
  for (var i = obj.length >>> 0; i--;) { 
    array[i] = obj[i];
  }
  return array;
}

//...
var divs = toArray(document.getElementsByTagName('div'));
//...

这篇关于在循环结构中将元素追加到DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆