/    Sign up×
Community /Pin to ProfileBookmark

Loop issues – getElementById is not getting the right ID

Hello all,

I have script that is suppose to add an onClick event to an anchor tag based on the parent ID. That works fine when implemented by its self. My problems arise when I put it into a loop. When I click the links in side the divs the Background for that div is suppose to change color. What’s happening instead is the background for the last div (the last element of the array) is getting it’s background changed.

I am sure this is a simple problem for someone out there.

Thanks for any help!

[code=html]
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Untitled Document</title>
<script type=”text/javascript”>
function start() {
var pageSections = new Array(“horse”, “cow”, “squirl”, “rhino”);

for (var i=0; i < pageSections.length; i++) {
var elementLink = document.getElementById(pageSections[i]).getElementsByTagName(‘a’);
var elementId = pageSections[i];
//alert(elementId)
for (var x=0; x < elementLink.length; x++) {
//alert(x + elementId)
elementLink[x].onclick = function() {
//alert(x + elementId)
document.getElementById(elementId).style.backgroundColor = “#F00”;
}
}
}
}
</script>
</head>
<body onload=”start()”>
<div id=”horse” style=”width:200px;height:300px;background: #EEE;”>
<a href=”#”>This is a test</a><br />
</div>
<div id=”squirl” style=”width:200px;height:300px;background: #EEE;”>
<a href=”#”>This is a test</a><br />
</div>
<div id=”cow” style=”width:200px;height:300px;background: #EEE;”>
<a href=”#”>This is a test</a><br />
</div>
<div id=”rhino” style=”width:200px;height:300px;background: #EEE;”>
<a href=”#”>This is a test</a><br />
</div>

</body>
</html>
[/code]

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@toicontienNov 08.2007 — This line of code is incorrect:
var elementId = pageSections[i]
It should be:
var elementId = pageSections[i][B].id[/B]
Copy linkTweet thisAlerts:
@matchesauthorNov 08.2007 — That give me undefined errors for elementID. Thanks for you quick response though!

[code=html]
function start() {
var pageSections = new Array("horse", "cow", "squirl", "rhino");

for (var i=0; i < pageSections.length; i++) {
var elementLink = document.getElementById(pageSections[i]).getElementsByTagName('a');
var elementId = pageSections[i].id;
alert(elementId)
for (var x=0; x < elementLink.length; x++) {
//alert(x + elementId)
elementLink[x].onclick = function() {
//alert(x + elementId)
document.getElementById(elementId).style.backgroundColor = "#F00";
}
}
}
}[/code]
Copy linkTweet thisAlerts:
@toicontienNov 08.2007 — Oh, I'm sorry. pagesections is an array of Ids already. You are trying to use elementId inside an onclick. That onclick function is executed in the scope of the link being clicked, not the scope of the start() function, so elementId simply doesn't exist. You'll want to use a function closure to get around this.

function start() {
var pageSections = ["horse", "cow", "squirl", "rhino"];

for (var i=0; i &lt; pageSections.length; i++) {
var elementLink = document.getElementById(pageSections[i]).getElementsByTagName('a');
var elementId = pageSections[i];
for (var x=0; x &lt; elementLink.length; x++) {
elementLink[x].onclick = [B]getLinkClickFn(elementId)[/B];
}
}
}


[B]function getLinkClickFn(id) {
return function() {
document.getElementById(id).style.backgroundColor = "#F00";
};
}[/B]

Try that code out.
×

Success!

Help @matches spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.21,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...