changing link state onload

This nicely adds a class to the link if the href is equal to the url:

function current()
{
      var lnk = document.links;
      for(var i=0;i<lnk.length;i++)
      {
            if(lnk[i].href.indexOf(self.location.pathname)>-1) lnk[i].className = "onstate";
      }
}

window.onload = function()
{
     current();
}

However, it applies to all links on the page. Ideally, I need it to "only" apply to the following container:

<ul id="navlist">
      <li><a id="nav1" href="one.html">menu link</a><li>
      <li><a id="nav2" href="two.html">menu link</a><li>
      <li><a id="nav3" href="three.html">menu link</a><li>
</ul>

The number of li tags is variable, but perhaps accessing GetElementById for navlist would be sufficient?

Thanks,
Sean
LVL 31
seanpowellAsked:
Who is Participating?
 
ZvonkoConnect With a Mentor Systems architectCommented:
Here an example:

<html>
<head>
<style>
.onstate {
  color: red;
}
</style>
<script>
function current(){
    var lnk = document.getElementById('navlist').getElementsByTagName('a');
    for(var i=0;i<lnk.length;i++)
    {
         if(lnk[i].href.indexOf(self.location.pathname)>-1) lnk[i].className = "onstate";
    }
}

window.onload = current;
</script>
</head>
<body>
<ul id="navlist">
    <li><a id="nav1" href="one.html">menu link</a><li>
    <li><a id="nav2" href="two.html">menu link</a><li>
    <li><a id="nav3" href="three.html">menu link</a><li>
</ul>
<ul>
    <li><a id="nav1" href="one.html">menu link</a><li>
    <li><a id="nav2" href="two.html">menu link</a><li>
    <li><a id="nav3" href="three.html">menu link</a><li>
</ul>
</body>
</html>



0
 
seanpowellAuthor Commented:
That's absolutely perect - you nailed it in one.

Thanks Zvonko :-)
Sean
0
 
ZvonkoSystems architectCommented:
You are welcome.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.