循环中的document.getElementById

时间:2013-01-04 13:53:04

标签: javascript

假设我想更改下面示例中具有类“the_class”的所有div的类。在循环遍历长列表(300 li和许多嵌套div标签)时添加编号id是一种很好的方法。或者在这种情况下document.getElementById会变慢吗?

由于我控制HTML / PHP添加ID对我来说不是问题。但我认为“document.getElementById”每次都会遍历整个文档。也许其他一些方法每次都不会循环,因此更快?

JAVASCRIPT

var data_length = document.getElementById('the_ul').getAttribute('data-length'),
    i = 0;
while(i++ < data_length) {
    document.getElementById('id_name' + i).className = 'a_new_class';
}

HTML

<ul id=the_ul data-length="2">
    <li>
        <div>
            <div>
                <div>content1</div>
                <div id=id_name1 class=the_class>content2</div>
                <div>content3</div>
            </div>
        </div>
    </li>
    <li>
        <div>
            <div>
                <div>content1</div>
                <div id=id_name2 class=the_class>content2</div>
                <div>content3</div>
            </div>
        </div>
    </li>
</ul>

1 个答案:

答案 0 :(得分:1)

另一种选择是document.getElementsByClassName

var el = document.getElementsByClassName("the_class")
for (var i = 0, ilen = el.length - 1; i < ilen; i++) {
    el[i].className = "a_new_class"
}

document.querySelectorAll

var el = document.querySelectorAll (".the_class")
for (var i = 0, ilen = el.length - 1; i < ilen; i++) {
    el[i].className = "a_new_class"
}

根据简单的Jsperf测试,document.getElementsByClassName似乎具有最佳性能。