Search code examples
javascripthtmlonclickgetelementsbynameparent-node

JavaScript change div color with link


This seems really simple but Im brand new to JavaScript. I have a link on my page. When you click this link 2 things happen. 1) Using html the page jumps to the location of the referenced anchor tag on the page. 2) The div that holds the link changes its background color.

HTML

<a href="#abcd"  onclick="makeRed(this.href);">Link to div on page</a>

<div id="abcd">
    <a name="abcd">Not a clickable link.</a>
</div>

JS

function makeRed(x) {
var highlight=x.slice(-4);
document.getElementsByName(highlight).parentNode.style.backgroundColor="red";
}

Firebug tells me document.getElementsByName(highlight).parentNode is undefined and this is where I'm confused.


Solution

  • Replace

    document.getElementsByName(highlight).parentNode.style.backgroundColor="red";
    

    with

    document.getElementsByName(highlight)[0].parentNode.style.backgroundColor="red";

    since getElementsByName returns an array