Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  183] [ 4]  / answers: 1 / hits: 15674  / 12 Years ago, fri, january 4, 2013, 12:00:00

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>

More From » javascript

 Answers
42

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.


[#81081] Thursday, January 3, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lexusg

Total Points: 718
Total Questions: 106
Total Answers: 104

Location: Palestine
Member since Tue, Jul 20, 2021
3 Years ago
;