How to iterate through ul list using Javascript?

dom, javascript

Solution

You should call `getElementsByTagName()` only once, caching the result.

Then iterate over the collection like this (instead of using `for/in`).

var a_elements = sender.parentNode.parentNode.getElementsByTagName("a");

for (var i = 0, len = a_elements.length; i < len; i++ ) {
    a_elements[ i ].style.color = 'blue';
    a_elements[ i ].style.backgroundColor = '#FFFFFF';
}
sender.style.color = '#FFFFFF';
sender.style.backgroundColor = '#000000';

To get the target, you can pass it as the parameter in the inline `onclick`:

   <ul>
        <li><a onclick="Paint(this)">About</a></li>
        <li><a onclick="Paint(this)">Contents</a></li>
        <li><a onclick="Paint(this)">Visual</a></li>
        <li><a onclick="Paint(this)">CSS</a></li>
        <li><a onclick="Paint(this)">Javascript</a></li>
    </ul>

Then your javascript can look like this:

function Paint( sender ) {

    var a_elements = sender.parentNode.parentNode.getElementsByTagName("a");

    for (var i = 0, len = a_elements.length; i < len; i++ ) {
        a_elements[ i ].style.color = 'blue';
        a_elements[ i ].style.backgroundColor = '#FFFFFF';
    }
    sender.style.color = '#FFFFFF';
    sender.style.backgroundColor = '#000000';
}

Example: http://jsbin.com/aroda3/

Problem

I have the following HTML page (page is simplified here as it is a sample of the real one): ``` <html> <head> <script type="text/javascript" src="JavaScript/Painting.js"></script> </head> <body> <div id="center-wrapper"> <div id="side-menu"> <ul> <li><a onclick="Paint()">About</a></li> <li><a onclick="Paint()">Contents</a></li> <li><a onclick="Paint()">Visual</a></li> <li><a onclick="Paint()">CSS</a></li> <li><a onclick="Paint()">Javascript</a></li> </ul> </div> </div> </body> </html> ``` And I have the Painting.js file (again, a bit simplified): ``` function Paint() { var e = window.event; var sender; if (e.target) { sender = e.target; } else { if (e.srcElement) { sender = e.srcElement; } } for (element in sender.parentNode.parentNode.getElementsByTagName("a")) { element.style.color = 'blue'; element.style.backgroundColor = '#FFFFFF'; } sender.style.color = '#FFFFFF'; sender.style.backgroundColor = '#000000'; } ``` The basic idea is: - Find a HTML element that caused the event. - Go up until you reach the `<ul>` element. - Loop through the list items; find the `<a>` tags and change their color and background - Upon exiting the loop, change the color and the background of the HTML element that caused the event. Now, I can't seem to get to the part located in the for loop. I think I am making a mistake by calling GetElementsByTagName() method. Could you help me out? Thanks.

Original source

Related problems