문제

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.

도움이 되었습니까?

해결책

Replace

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

with

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

since getElementsByName returns an array

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top