循环遍历div的所有后代-仅限于JS [英] Loop through all descendants of a div - JS only

查看:269
本文介绍了循环遍历div的所有后代-仅限于JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用jQuery来做到这一点:

I've been using jQuery to do this:

$element.find("*").each(function() {
    var $this = $(this);

    $this.removeAttr("style width align");

    if ($this.is("embed")) {
        $element.append("<div class='video'></div>");
        $this.attr("width", 640).attr("height", 360).parent().appendTo("#" + element + " .video");
    };
});

但是我一直在读,与简单的for循环相比(

But I've been reading that jQuery's .each() method is quite slow when compared to a simple for loop (jsPerf). My question is how can I mimic this with pure JS? Find all elements within a div, then loop through the nodes.

我尝试搜索此内容,但似乎只能找到jQuery答案-随处可见.

I've tried to search for this but all I can seem to find are jQuery answers - everywhere.

我尝试了其他方法,但这与我选择所有后代的时间差不多:

I've tried other things but this was as close as I got to selecting all descendants:

var children = document.getElementById('id').getElementsByTagName('*');

for( var i = 0; i<children.lengtth; i++){
    children[i].removeAttribute("style");
    console.log(children[i]);
}

推荐答案

您已经做对了

var ancestor = document.getElementById('id'),
    descendents = ancestor.getElementsByTagName('*');
    // gets all descendent of ancestor

现在,您只需要遍历children

var i, e, d;
for (i = 0; i < descendents.length; ++i) {
    e = descendents[i];
    e.removeAttribute('style');
    e.removeAttribute('width');
    e.removeAttribute('align');
    if (e.tagName === 'EMBED') {
        d = document.createElement('div');
        d.setAttribute('class', 'video');
        ancestor.appendChild(d);
    }
}

根据您正在执行的操作,因为您正在使用getElementsByTagName获取descendents,所以descendents live NodeList ,因此它的长度当您向ancestor添加更多节点时,它会发生变化.如果您需要避免这种情况,请在循环之前将其转换为 Array

Depending on what you're doing, because you're using getElementsByTagName to get descendents, descendents is a live NodeList, so it's length will change as you add more Nodes to ancestor. If you need to avoid this, convert it to an Array before the loop

decendents = Array.prototype.slice.call(decendents);

有关可重用功能,请参见此要点.

See this gist for a reusable function.

这篇关于循环遍历div的所有后代-仅限于JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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