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); }
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).
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.
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.
The wrap() method wraps specified HTML element(s) around each selected element.
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');
$('<div/>', {'class': divClass}).append($('<span/>', {'class': spanClass}));
Why not:
$('<div/>').addClass(divClass).append($('<span/>').addClass(spanClass));
IE create your div first?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With