Search code examples
jqueryhtml-manipulation

jQuery: wrap newly created html


I create HTML snippet on-the-fly:

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

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

Semantically I want to do:

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

that does not work. So I just want following jQuery-idiomatic version:

function wrap(what, with) { return $(with).append(what); }

Solution

  • Keep in mind that your jQuery object is still referencing the new <span>, so if you're trying to insert it with a chained method, the <div> won't be inserted.

    To overcome this, you'd need to traverse up to the new parent <div> first.

        // 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 could also write it like this:

    $('<span/>').addClass(spanClass).wrap('<div/>')
                .parent().addClass(divClass).appendTo('body');