views:

48

answers:

2

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...

+4  A: 
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 );
}
poke
That will go multiple levels deep, so if it's a nested list, it will have an adverse effect by processing `li` s it should leave alone. Given the structure, just `document.getElementById('tabbed-boosts').firstChild.childNodes` will do it provided there are no text nodes from whitespace.
T.J. Crowder
@T.J. Crowder: I believe it's always okay to abstract a solution the way you need it. I usually wouldn't want to edit some lis, if I don't already know how the DOM structure looks like, so I can safely assume that the way to select the lis is good enough. And after all it's just an example.
poke
I actually lied and it was an A element that I needed but this ended up working: document.getElementById('tabbed-boosts').getElementsByTagName('a')[0].className="tab"
spyderman4g63
A: 

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;
}
EC182