Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - use wrap() to wrap multiple elements?

Tags:

jquery

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!

like image 766
Probocop Avatar asked Aug 13 '10 09:08

Probocop


People also ask

What does wrap do in jQuery?

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

How do you wrap an element in JavaScript?

function wrap_single(el, wrapper) { el. parentNode. insertBefore(wrapper, el); wrapper. appendChild(el); } let divWrapper; let elementToWrap; elementToWrap = document.

Can you wrap a div in an a tag?

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.


2 Answers

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()

like image 102
jAndy Avatar answered Sep 21 '22 06:09

jAndy


$('input+label').each(function(){     $(this).prev().andSelf().wrapAll('<div>'); });​ 
like image 25
James Avatar answered Sep 20 '22 06:09

James