Forum Moderators: open

Message Too Old, No Replies

Accessing a specific element

within a div

         

ggrot

3:21 am on Feb 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have some html that looks like:

<div id="MyID">text and a <a href="http://www.google.com/">link</a></div>

I can access the div using document.getElementById('MyID').style.color="#FFFFFF" for example. But what if I want to change the style of just the link. In css it would look something like:


#MyID.a {
color=#FFFFFF;
}

But I would like to update this on the fly. And no I can't put an id field in the anchor tag. Any ideas?

birdbrain

9:37 am on Feb 17, 2005 (gmt 0)



Hi there ggrot,

try it like this...

script

[blue][2]
<script type="text/javascript">
<!--
function changeLink(el) {
if(el.firstChild.nextSibling.nodeType==1) {
el.firstChild.nextSibling.style.color="#f00";
}
}
//-->
</script>[/2][/blue]

html
[blue][2]
<div onmouseover="changeLink(this)">
text and a
<a href="http://www.google.com/">link</a>
</div> [/2]
[/blue]

birdbrain

Bernard Marx

11:37 am on Feb 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The function very sensibly checks nodeType before acting. This is good because browsers very often enter 'phantom' text nodes that mess up child & sibling indexing. The function prevents an error...but doesn't do anything about it.

function changeLink(el) { 
el.getElementsByTagName('a')[0].style.color="#f00";
}

This one will work, phantom nodes or no, and will continue to work if you put format-related tags on the DIVs text.

ggrot

11:00 pm on Feb 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Awesome thats exactly what I was looking for. You do not understand how long i spent searching for this on Ggle.