Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Javascript to add a CSS id 1

Status
Not open for further replies.

steve100

Technical User
Aug 15, 2002
35
0
0
GB

Hi can anyone help?, I want to use JS to add an XHTML id="selected" attribute to the link which is the same as the H1 header on a page. This attribute will be picked up by a CSS file and have a style applied to it to differentiate it as a 'you are here' link.

This is what I did:

<!-- call function from web page -->
<body class="body-class" id="bodyid" onload="you_are_here()">


In the JS file:

// execute function
function you_are_here() {

// get list of anchor links
var a = getElementsByTagName("a");

//get header
var h1 = getElementsByTagName("h1");

// loop through each link looking for a match
for (i=0; i < a.length; i++) {

// if link matches document h1 then set the id attribute on the link to 'selected'
if (a == h1) {
return a.setAttribute("id", "selected");
}

}

}


This style is in the CSS file:

#selected {
background-color:#eeeeee;

}

It didn't work, does anyone know how this can be done with JS?

thanks
Steve

 
First, getElementsByTagName is document method (use document.getElementsByTagName()).

Second, I don't get the logic... H1 elements are always different than A. Can you post sample HTML code?
 
Hi I was hoping that the content of an "a" element could be compared to the content of a H1 element where they both have the same text.

E.g on the home page my H1 would be <h1>home</h1> and in my navigation I would have a link called <a href="index.htm">home</a>

Can the text from these two tags not be compared?.

Steve
 
In that case don't compare elements - compare content inside tags (innerHTML).
Also: getElementsByTagName() returns collection, so use h1[0] instead of h1:
Code:
for (i=0; i < a.length; i++)
	if (a[i].innerHTML == h1[0].innerHTML)
       return a[i].setAttribute("id", "selected");
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top