javascript change element background

javascript

Solution

Well, the `setAttribute` function doesn't do what you think it does.

If you inspect the elements in your jsfiddle, you see this:

... <p backgroundcolor="red" ...>

and this is definitely not what you want. What you want is something like this:

setAttribute("style", "background-color: red;");

so it will transform into

... <p style="background-color: red;" ...>

Problem

This is the HTML ``` <p>texjksdgfjl sdjfg sjdfg</p> <p>&nbsp;</p> <p>texjksdgfjl sdjfg sjdfg</p> <p>&nbsp;</p> <p>texjksdgfjl sdjfg sjdfg</p> ``` This is the JavaScript ``` var d = document.getElementsByTagName("p"); for (var i=0;i<d.length;i++) { var text = d[i].textContent; if (text.length===1){ d[i].style.background ='blue'; } else { d[i].setAttribute("backgroundColor", "red"); } } ``` (Obviously) I can do what I want to do - different background for p elements that contain some text as opposed to p elements which are generated as < p > & nbsp; < /p > But why doesn't the setAttribute work? I must be missing something very simple, but for the life of me I cannot imagine what it is. Pure JS please, no jQuery, no MooTools, no other library. Here is the test fiddle: enter link description here

Original source