Reputation: 4309
How do I modify the style of the li element using DOM?
<div id="tabbed-boosts">
<ul>
<li>test1</li>
<li>test2</li>
<li>test3</li>
</ul>
</div>
getElementById('tabbed-boosts').childNodes will get me to the UL, how do I modify the LI?
Also needs to work in IE6...
Upvotes: 2
Views: 96
Reputation: 598
The issue with using document.getElementById( 'tabbed-boosts' ).getElementsByTagName( 'li' ) will show up if you start using nested lists. Using childNodes property will give you access to the direct children of that particular ul element. For example
<ul id='tabbed-boosts'>
<li>...</li>
<li>
<ul>
<li> ... </li>
</ul>
</li>
<li>... </li>
</ul>
using getElementsByTag will return ALL the 'li' elements within tabbed-boosts sub-tree, where childNodes will only return the first level 'li' elements. In the example above you'd receive a collection of 4 elements using getElementById, including the nested LI whereas you would only receive a collection of 3 li elements using myUl.childNodes (shown below)
var myUl = document.getElementById('tabbed-boosts');
var myLi = myUl.childNodes;
for(var i = 0; i<myLi.length; i++)
{
myLi[i].style....;
// do whatever you want to the li items;
}
Upvotes: 0
Reputation: 387677
var lis = document.getElementById( 'tabbed-boosts' ).getElementsByTagName( 'li' );
for ( var i = 0; i < lis.length; i++ )
{
lis[i].style.backgroundColor = '#' + Math.round( Math.random() * 0xFFFFFF ).toString( 16 );
}
Upvotes: 4