lolalola
lolalola

Reputation: 3823

jquery create a new object and insert html text

i create new div, and how insert text(html text) in this new div?

var div_obj = $(document.createElement("div")).attr({'class': 'test'}).css({'width' : size, 'height' : height, 'background' : bg});

I try:

div_obj.innerHTML = "text";

But don't work.

Upvotes: 1

Views: 4126

Answers (3)

wsanville
wsanville

Reputation: 37516

You're close, but you're mixing the native DOM method calls with jQuery methods. Try this:

$('<div>').addClass('test').css({'width': size, 'height': height, 'background': bg}).html('text');

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630569

Use .html() here, like this:

div_obj.html("text");

.innerHTML is a DOM element property (not a jQuery object one), to access it you'd need to get the raw <div> DOM element, like this:

div_obj[0].innerHTML = "text";

As an aside: in jQuery 1.4+ there's a shorthand for creation, $(html, props), like this:

$("<div/>", { 'class': 'test', 
               css: {'width' : size, 'height' : height, 'background' : bg}, 
               html: 'text' });

Upvotes: 4

Cubed Eye
Cubed Eye

Reputation: 5631

$('div').html('html text');

but you should really give the div an id so it can be referenced by jquery without altering the content of other divs

Upvotes: 0

Related Questions