[thelist] JavaScript - searching for link and comparing

Peter-Paul Koch pp.koch at gmail.com
Wed Dec 22 04:11:29 CST 2004


> I'm a neophyte when it comes to Javascript. I'm trying to write some code
> that will search through my nav for a link matching the current page, and
> then write a css class to the containing <li> to style it as the current
> page the user is on.

var x = document.getElementById('nav').getElementsByTagName('a');
for (var i=0;i<x.length;i++)
{
  if (x[i].href == location.href)
    x[i].className = 'youarehere';
}
 
As several people pointed out this can be done through CSS, too, but
in my opinion this is a very complicated solution that is very badly
portable and maintainable, since it requires a gazillion classes and
you can't generate the BODY tag through, say, SSI.

If you insist on making the link to the current page normal text, do

var x = document.getElementById('nav').getElementsByTagName('a');
for (var i=0;i<x.length;i++)
{
  if (x[i].href == location.href)
    x[i].parentNode.replaceChild(x[i].firstChild,x[i]); // untested
}
 

> The nav menu is structured like this:
> 
> <ul id="nav">
> <li><a href="../aldermen/index.htm">Aldermans Office</a></li>
> <li><a href="../aldermen/index.htm">Home Page</a></li>
> <li><a href="../aldermen/block_parties.htm">Block Parties</a></li>
> </ul>

-- 
-------------------------------------------------------------------
ppk, freelance web developer

Bug Report: Report bugs yourself, or comment on previously 
reported ones.
http://www.quirksmode.org/bugreports/
------------------------------------------------------------------


More information about the thelist mailing list