Welcome to WebmasterWorld Guest from 54.224.96.57

Forum Moderators: open

Message Too Old, No Replies

Using JavaScript CSS to change color of child item

     
5:29 pm on Nov 8, 2006 (gmt 0)

Preferred Member

10+ Year Member

joined:Aug 12, 2005
posts:411
votes: 0


I have a link with an id, wrapped by a list item.

<li id="i"><a href="...">...</a></li>

Using CSS, I can control the color of the link by using the following command:

#i a{color:#abcdef}

Using JavaScript CSS, I can control the color of the list item using:

document.getElementById("i").style.color="#abcdef";

But how can I use JavaScript CSS to control the color of the link in the list item id?

Thanks

5:45 pm on Nov 8, 2006 (gmt 0)

Senior Member from GB 

WebmasterWorld Senior Member 10+ Year Member

joined:Oct 2, 2003
posts: 954
votes: 4


Hi there Jeremy_H,

does this help...


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">
<!--
window.onload=function(){
document.getElementById('foo').onclick=function(){
document.getElementById('i').firstChild.style.color='#abcdef';
return false;
}
}
//-->
</script>

</head>
<body>

<ul>
<li id="foo"><a href="#">click this link</a></li>
<li id="i"><a href="#">to change this color</a></li>
</ul>

</body>
</html>

birdbrain

6:19 pm on Nov 8, 2006 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts:4987
votes: 12


You could get the child <a> nodes of that list item.

var li = document.getElementById("i");
var anodes = li.getElementsByTagName("a");

Then loop through anodes and apply the style that way. Though you'd probably be better off defining a class and just assigning that class to the list item. For example:

li.selectedItem a { color: #abcdef; }

And then just attach the class to the list item instead of trying to directly modify the style attribute. Easier to maintain.