Choosing pairs of html elements in jquery

I am working with some server code that generates html that looks something like this:

<input type="radio" /> <label>something</label> <input type="radio" /> <label>something</label> <input type="radio" /> <label>something</label> <input type="radio" /> <label>something</label> 

I want to wrap each pair in between, but I cannot determine how to select pairs of elements in jquery to use wrapAll() for them. I cannot change the html I'm working with. Can anyone help?

+6
source share
3 answers
 $('input').each(function(){ $(this).next('label').add(this).wrapAll('<span>'); }); 
  • next will find the closest sibling.
  • add will add the corresponding item to the collection.

Demo

+11
source

You can try this.

 $('input').each(function(){ $(this).next().andSelf().wrapAll('<span>'); }); 
+3
source
+2
source

Source: https://habr.com/ru/post/903780/


All Articles