Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript change element background

Tags:

javascript

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

like image 945
flish Avatar asked Oct 29 '25 20:10

flish


2 Answers

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;" ...>
like image 65
alestanis Avatar answered Nov 01 '25 10:11

alestanis


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"
like image 41
Ben McCormick Avatar answered Nov 01 '25 09:11

Ben McCormick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!