I have an html div element in a variable
var rows = "";
rows += "<div>1111 : Hi there</div>";
I have tried to add background color to this div by following but everything failed.
1. $(rows).css({'background-color':'#FF0000'});
2. $(rows).css({'background-color':'#FF0000 !important'});
3. $(rows).css({backgroundColor:'#FF0000'});
4. $(rows).css({backgroundColor:'#FF0000 !important'});
5. $(rows).css('background-color','#FF0000');
6. $(rows).css('background-color','#FF0000 !important');
7. $(rows).find('div').css({'background-color':'#FF0000'});
8. $(rows).find('div').css({'background-color':'#FF0000 !important'});
9. $(rows).find('div').css({backgroundColor:'#FF0000'});
10. $(rows).find('div').css({backgroundColor:'#FF0000 !important'});
11. $(rows).find('div').css('background-color','#FF0000');
12. $(rows).find('div').css('background-color','#FF0000 !important');
May be there is selector problem but got
Object[div]
output from console.log($(rows));
So I think selector is working fine.
After adding css, this div is appended to other div
$("#parentDiv").append(rows);
After inspecting from firebug
I got only <div id='parentDiv'><div>1111 : Hi There</div></div>
there is no css added to this div.
If I use inline css it is working fine so I think there is no css to override color
rows += "<div style='background-color:#FF0000'>1111 : Hi there</div>";
jQuery is working fine for other things.
What is wrong with this code, Can anybody help please....
Thanks.
element need to exist in DOM to apply css
try this :
var rows = "";
rows += "<div>1111 : Hi there</div>";
// new element
var newEl = $("#parentDiv").append(rows);
newEl.find('div').css({'background-color':'#FF0000'});
try this
var rows = $('<div />',{text:"1111 : Hi there"});
rows.css({'background-color':'#FF0000'});
or
$("#parentDiv").append(rows).find('div').css({'background-color':'#FF0000'});
You need to store the result of $(rows).css to a variable and use that variable to append to parentDiv.
var rows = "";
rows += "<div>1111 : Hi there</div>";
var result = $(rows).css("background-color", "red");
$("#parentDiv").append(result);
You have two options. First:
var rows = "";
rows += "<div>1111 : Hi there</div>";
// rows only contains a string
rows = $(rows).css({'background-color':'#FF0000'});
Now rows will contain the new background color. jQuery will convert the string to an extended dom object and then use the .css function on it, but you have to store the returned value, the original string will not be touched.
Second option:
var rows = $("<div>1111 : Hi there</div>");
// now rows contains a jQuery extended dom object
rows.css({'background-color':'#FF0000'});
Now all jQuery functions on this object work and the object is manipulated directly, no need to store the returned value.