How to iterate through ul list using Javascript?

Viewed 67058

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:

  1. Find a HTML element that caused the event.
  2. Go up until you reach the <ul> element.
  3. Loop through the list items; find the <a> tags and change their color and background
  4. 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.

5 Answers

You can get the ul element with document.getelementbyid and then use the "children" property of the element which is a list of the list elements inside it.

Related