Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  8] [ 5]  / answers: 1 / hits: 27139  / 11 Years ago, fri, march 8, 2013, 12:00:00

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


More From » javascript

 Answers
43

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; ...>

[#79730] Thursday, March 7, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taliac

Total Points: 84
Total Questions: 114
Total Answers: 114

Location: Morocco
Member since Fri, May 22, 2020
4 Years ago
taliac questions
Sun, Mar 21, 21, 00:00, 3 Years ago
Tue, May 12, 20, 00:00, 4 Years ago
Mon, Jan 13, 20, 00:00, 4 Years ago
;