How would I go about using wrap()
to wrap multiple elements (with different classes) inside a <div>
?
For example, on the form I'm working on there is a big list of checkbox inputs and labels in the form of:
<input> <label> <input> <label>
etc
I'm wanting to wrap a <div>
around the input and label, so the result would be:
<div> <input> <label> </div> <div> <input> <label> </div>
Thanks!
jQuery wrap() Method The wrap() method wraps specified HTML element(s) around each selected element.
function wrap_single(el, wrapper) { el. parentNode. insertBefore(wrapper, el); wrapper. appendChild(el); } let divWrapper; let elementToWrap; elementToWrap = document.
In general, you can't have an inline element, like an anchor (<a>) or span, wrap around a block level element like a division (<div>) or heading.
You can use the .wrapAll()
method.
$('form > input').each(function(){ $(this).next('label').andSelf().wrapAll('<div class="test"/>'); });
If your markup has always the exact same order, I'd prefer to use:
var $set = $('form').children(); for(var i=0, len = $set.length; i < len; i+=2){ $set.slice(i, i+2).wrapAll('<div class="test"/>'); }
Should be significant faster.
Ref.: .wrapAll(), .andSelf(), .slice()
$('input+label').each(function(){ $(this).prev().andSelf().wrapAll('<div>'); });
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