Creating DIV's in jQuery

77 views Asked by At

The following code works for me:

var div2 = document.createElement('DIV');
$(div2).css('position','relative').insertBefore( $(div).children()[0] );
var div3 = document.createElement("DIV");
$(div2).prepend($(div3).css({'display':'inline','position':'absolute'}));

...but I got to imagine there is a neater jQuery way to do the createElement's. I tried the following, but it didn't work:

$('<div></div>').css('position','relative').insertBefore( $(div).children()[0] );
$(div2).prepend($('<div></div>').css({'display':'inline','position':'absolute'}));

Any sugestions?

2

There are 2 answers

0
gasp On

You can use the $("<div></div>") syntax to create elements without using document.createElement('div');

var d = $("<div></div>").text("hello");
$("body").append(d);

This works perfectly, (please check on fiddle http://jsfiddle.net/P5A8L/1/ ) your error may come from the undefined variables div and div2

0
wrxsti On
$('body').append('<div>This is my div.</div>').css({'display':'inline','position':'absolute'});

You can feel free to replace 'body' with any selector you want, or the method to prepend, after, before. They should all work. Just a simple one liner. No need to create variables. At least if I understand your question correctly.