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>
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>
Share
Improve this question
asked Jan 4, 2013 at 13:53
user1087110user1087110
3,78311 gold badges37 silver badges43 bronze badges
2
- 4 see getElementsByClassName or querySelectorAll. Note browser restrictions. – jbabey Commented Jan 4, 2013 at 13:55
- Thanks jbabey. Do you mean that getElementsByClassName will be faster than my method? – user1087110 Commented Jan 4, 2013 at 14:12
1 Answer
Reset to default 1An 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.