简体   繁体   中英

document.getElementById in loop

Let's say I want to change class for all div's that have class "the_class" in the example below. Would it be a good approach to add numbered id's when looping through a long list (300 li's and many nested div tags). Or will document.getElementById be slow in this case?

Since I control the HTML/PHP adding ID's is not a problem for me. But I figure that "document.getElementById" will loop through the whole document each time. Maybe some other method woudl not loop through the whole each time and therefore be faster?

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>

An alternative would be 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"
}

or 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"
}

According to a simple Jsperf test, document.getElementsByClassName seems to have the best performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM