Changing background color with class

Here’s the html:

<div id="buttons">
   <button id="reset" onclick="reset()">Reset</button>
</div>

here’s the javascript:

function reset() {
   document.getElementsByClassName('pixel').style.backgroundColor = "white";
}

The reset button should set the pixels(I mean boxes that are 40px wide and 40px high) white so it whould look like they’re resetted.
Why i can’t set the background color of these “boxes” in javascript?
Here’s the link of my project.

2 Likes

You only have the color white for the JS. I think that is the problem.

I hope this helps =)

If this doesn’t help, please let me know!

2 Likes

The problem here is that you cant reset the color of all elements at once.

document.getElementsByClassName('pixel') contains all the elements with the class pixel. This means it is a collection/array. And thus does not have a style attribute.

Here is a solution that does work.

function reset() {
	var elements = document.getElementsByClassName('pixel'); // get all elements
	for(var i = 0; i < elements.length; i++){
		elements[i].style.backgroundColor = "white";
	}
}

what we did different is we first get all the elements on the field and than loop through them since they DO have a style attribute individually.

2 Likes

Thank you for the reply it worked

1 Like

Thank you again for the help. :grinning:

1 Like

Your welcome @lolfail!

1 Like

@lolfail You have no class; Named pixel, So this isn’t generated how you wanted.
The code should be:

<div id="buttons">
<button id="reset" onclick="reset()">Reset</button>
</div>

JS:

function reset(){
    document.getElementById("reset").style.backgroundColor = "#FFF";
}

I think this is a more styled way of doing it:
JS:

function reset(){
   document.getElementById("reset").innerHTML = "Reseted!";
document.getElementById("reset").style.backgroundColor = "#FFF"
}

HTML:

<div id="buttons">
<button id="reset" onmousedown="reset()">Reset</button>
</div>

Hope this helps!

1 Like

This wont work will it. The problem here is that, if you use the id to get to the elements you will get at all times one and only one element. Since the field that needs to be reseted exists out 25 elements it is not possible to use the id in this instance. Unless you want to copy paste code, but this should be avoided at all times.

There is surely a class pixel present. You might want to click the link that go’s to his code.

1 Like

Yes thank you. Yours worked :grinning:

1 Like

@biira I seen the code.

1 Like