Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  29] [ 6]  / answers: 1 / hits: 15784  / 13 Years ago, thu, february 23, 2012, 12:00:00

I want to change the background image of a button using Javascript. Here is what I am currently trying, but it is failing.



HTML code -



      <tr id=Rank1>
<td><button class=darkSquare></button></td>
<td><button class=lightSquare ></button></td>
<td><button class=darkSquare ></button></td>
<td><button class=lightSquare ></button></td>
<td><button id=e1 class=darkSquare ></button></td>
<td><button class=lightSquare ></button></td>
<td><button class=darkSquare ></button></td>
<td><button class=lightSquare> </button></td>
</tr>


JavaScript Code



        initializer();

function initializer()
{
var tableRow = document.getElementById(Rank1);

var buttons = tableRow.getElementsByTagName(button);

for(b in buttons)
{
console.log(b.toString());
b.style.backgroundImage = url('darkSquare.jpg');
}
}


In the console, I get an error saying b.style is undefined.


More From » button

 Answers
16

for (... in ...) loops do not work that way in JavaScript it should be:



for (var b = 0; b < buttons.length; b++) {
buttons[b].style.backgroundImage = url('darkSquare.jpg');
}


for (... in ...) actually iterates over all the members of an object



eg. using var x = {a: 1, b: 2, c: 3} in for(var m in x) console.log(m) will produce



> a
> b
> c


it kind of works with arrays because it considers the indices members like this:



var x = [1,2,3];
for (var m in x) console.log(m);
> 0
> 1
> 2


since it is giving you the indices as if they were members you can't distinguish. the pitfall is:



var x = [1,2,3];
x.stuff = 'boo!';
for (var m in x) console.log(m);
> 0
> 1
> 2
> stuff


General Rule of Thumb: only use for (... in ...) when iterating over members in an object, use for (var i = 0; i < array.length; i++) when using arrays



you can always cheat and use:



for (var i = 0, item = x[i]; i < x.length; item=x[++i]) {
// now item is the current item
}

[#87265] Wednesday, February 22, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dayana

Total Points: 302
Total Questions: 102
Total Answers: 100

Location: Cayman Islands
Member since Fri, Mar 4, 2022
2 Years ago
;