0

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?

  • Possible duplicate of [jQuery document.createElement equivalent?](http://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent) There are several other questions that answer this as well. – justisb Dec 10 '13 at 21:17
  • `$("
    ", {css: {position:'relative'}}).prependTo(div) `
    – megawac Dec 10 '13 at 21:18

2 Answers2

0

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

gasp
  • 576
  • 4
  • 10
0
$('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.

wrxsti
  • 3,434
  • 1
  • 18
  • 30