How to change button background image using javascript?

I want to change the background image of a button using Javascript. That's what I'm trying now, but it fails.

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')";
            }
         }

An error message appears in the console: b.style undefined.

+1
source share
3 answers

for (... in ...) loops do not work this way in JavaScript, this 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 the object

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

> a
> b
> c

it works with arrays because it considers such index elements as follows:

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

because it gives you indexes as if they were members that you cannot distinguish. trap:

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

: for (... in ...) , for (var i = 0; i < array.length; i++)

:

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

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

, , b. hasOwnProperty, , , , .

for-in

for(var b in buttons)
{
    if (buttons.hasOwnProperty(b))
        buttons[b].style.backgroundImage = "url('darkSquare.jpg')";
}​
+1

for ( ... in .... ) - , :

for( b in buttons ) {
    buttons[b].style.backgroundImage = "url('darkSquare.jpg')";
}

jsFiddle

+1

All Articles