Plamen Dobrev
Plamen Dobrev

Reputation: 13

JavaScript: My for loop seems to be not working when I am trying to work with DOM

The thing is, the problem seems to be coming from the for loop itself. When I delete the code inside it and put alert(c);, for example, it's not doing anything. I used the same method earlier for just a little bit different thing and it's working perfectly. Here's what I did with my earlier problem:

for (var b = 0; b <= 99; b++) {
    var boxTwo = document.querySelectorAll(".icon2.windowbg[style]")[b];
    boxTwo.style.backgroundColor = "#552222";
}

It works completely fine. Unfortunately, I can't say the same thing about my new problem:

for (var c = 0; c <= 99; c++) {
    var boxOneNew = document.querySelectorAll(".icon1.windowbg.topicnew")[c];
    boxOneNew.style.backgroundColor = "#552222";
}

Upvotes: 1

Views: 32

Answers (2)

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

You have to take the boxTwo out of your loop, and loop condition should be boxTwo.length to prevent from error style of null unless your boxTwo length is 98.

var boxTwo = document.querySelectorAll(".icon2.windowbg[style]");
for (var b = 0; b < boxTwo.length; b++) {
  boxTwo[b].style.backgroundColor = "#552222";
}

Do it for your second code as well:

var boxOneNew = document.querySelectorAll(".icon1.windowbg.topicnew");
for (var c = 0; c < boxOneNew.length; c++) {
  boxOneNew[c].style.backgroundColor = "#552222";
}

Note: make sure that .icon1.windowbg.topicnew match something in the DOM.

Upvotes: 1

Plamen Dobrev
Plamen Dobrev

Reputation: 13

As you wanted,

<td class="icon1 windowbg topicnew">...</td>

The other part of the code is pretty much the same thing, it just doesn't have the 'topicnew' class. What I am trying to do is change this element's background color. And yes, there are 99 elements.

Upvotes: 0

Related Questions