JavaScript change div color with link

770 views Asked by At

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.

2

There are 2 answers

1
Michael Sazonov On BEST ANSWER

Replace

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

with

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

since getElementsByName returns an array

1
Paul Butcher On

getElementsByName returns a list (hence "...Elements...", rather than "...Element..."). Lists don't have parentNodes.

Either use getElementById to reference a single element with a given id, or iterate over the list returned by getElementsByName until you find the exact element you are looking for.