Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); }
like image 262
THX-1138 Avatar asked Jan 12 '11 16:01

THX-1138


People also ask

What does the jQuery wrap () function do?

jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function. Syntax: $(selector).

What is slice () method in jQuery?

slice() method constructs a new jQuery object containing a subset of the elements specified by the start and, optionally, end argument. The supplied start index identifies the position of one of the elements in the set; if end is omitted, all elements after this one will be included in the result.

What is wrapped set in jQuery?

The wrapped set is simply a list of DOM elements(with their children) in the order in which they are defined in the current document that matches a selector or in the order in which they have been created on the fly with the $(html) function.

Which jQuery method allows you to add a wrapper element around another set of elements?

The wrap() method wraps specified HTML element(s) around each selected element.


3 Answers

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');
like image 154
user113716 Avatar answered Oct 26 '22 12:10

user113716


$('<div/>', {'class': divClass}).append($('<span/>', {'class': spanClass}));
like image 24
Tomalak Avatar answered Oct 26 '22 12:10

Tomalak


Why not:

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

IE create your div first?

like image 1
Jason Benson Avatar answered Oct 26 '22 14:10

Jason Benson