View Full Version : change id by url

04-16-2005, 11:24 PM
Hi there,

I'm a total javascript newbie, but I figure my request is pretty basic for someone with any experience.

I have a navigation in unordered list < ul > format. I apply an id of "active" to the anchor <a id="active"> within a list item <li> in order to indicate the current section/page. Here is a sample of what it would look like for the 'about' section:

<li><a href="/about" id="active">About</a></li>
<li><a href="/contact">Contact</a></li>

I would like to generate the 'active' id automatically, I'm assuming by using location.href even if it means using absolute URL's.

So I was thinking something like:

function setactivestate() {
if (document.getelementbyhref) <-- I know this doesn't exist but that's where you're supposed to help me!
var nodeobj = document.getelementbyhref;
if nodeobj = location.href {
nodeobj.id = active;

I know this is probably very simplistic, but maybe someone could tweak it to work.

The caveat is I'd like to have it so that it would apply the 'active' id to the 'about' link when you're on domain.com/about, but also when you're on a sub page in that section like domain.com/about/philosophy.html.

04-16-2005, 11:40 PM
You could use this function:

function setActiveState() {
var anchors = document.getElementsByTagName("A");

for( var i=0; i<anchors.length; i++ ) {
if( anchors[i].getAttribute( "href" ) == location.href ) {
anchors[i].setAttribute( "id", "active" );

Haven't tested it, but it should work.

Mr J
04-16-2005, 11:49 PM
Sorry, misunderstood the question