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.
for (... in ...)loops do not work that way in JavaScript it should be:for (... in ...)actually iterates over all the “members” of an objecteg. using
var x = {a: 1, b: 2, c: 3}infor(var m in x) console.log(m)will produceit kind of works with arrays because it considers the indices members like this:
since it is giving you the indices as if they were members you can’t distinguish. the pitfall is:
General Rule of Thumb: only use
for (... in ...)when iterating over members in an object, usefor (var i = 0; i < array.length; i++)when using arraysyou can always cheat and use: