This is the HTML
<p>texjksdgfjl sdjfg sjdfg</p>
<p> </p>
<p>texjksdgfjl sdjfg sjdfg</p>
<p> </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
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;" ...>
backgroundColor isn't an attribute on HTML elements. You can use bgcolor, but its really better to do this with CSS.
You can add a class to the node like this:
d[i].className += " myClass";
and then set a CSS rule
.myClass
{
backgroundColor: "red"
}
Or if you insist on hardwiring it to the DOM you can use
d[i].style.backgroundColor = "red"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With