JQuery: wrap newly created html

I create an HTML snippet on the fly:

$('<span/>').addClass(spanClass)

Is there a jQuery way to port this code to <div>?

Semantically I want to do:

$('<span/>').addClass(spanClass).wrap($('<div/>').addClass(divClass))

what does not work. So I just want to use the jQuery-idiomatic version :

function wrap(what, with) { return $(with).append(what); }
+5
source share
4 answers

Keep in mind that your jQuery object is still referencing a new one <span>, so if you try to insert it using the chain method, <div>it will not be inserted.

To overcome this, you must first go to the new parent element <div>.

    // Traverse up to the new parent in order to append the <div> and <span>
$('<span/>').addClass(spanClass).wrap($('<div/>').addClass(divClass))
            .parent().appendTo('body');

You can also write it like this:

$('<span/>').addClass(spanClass).wrap('<div/>')
            .parent().addClass(divClass).appendTo('body');
+11
source
$('<div/>', {'class': divClass}).append($('<span/>', {'class': spanClass}));
+4

:

$('<div/>').addClass(divClass).append($('<span/>').addClass(spanClass));

IE div?

+1

:

$('<span/>').addClass(spanClass).wrap($('<div/>').addClass(divClass).html()); 

$('<div/>').addClass(divClass).append($('<span/>').addClass(spanClass));
0

All Articles