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