javascriptdom-eventsgetelementsbytagname

How do I dynamically access elements of a particular Div tag?


This is my JavaScript's onMouseOver event handler for Div tags. (It works fine, in at least Chrome and IE):

function changeCallout(sender, e) {
    document.getElementById(sender.id).className = "callout2";
}

What I would like to be able to do is to set the color property of the H2 tag contained within the Div that is having it's class changed.

I know I should be able to access either the color property or change the class, but I'm not able to figure out how to access only the appropriate H2 tag (I'm aware of getElementsByTagName). What's the syntax to do this?


Solution

  • Assuming the wanted h2 is the first one under the target div, then use the following to search relative to that div:

    var div = document.getElementById(sender.id);
    var h2 = div.getElementsByTagName("h2")[0];
    

    If it's not the first one, simply change 0 to n (on the second line) where n is the position of the desired header.