boz
boz

Reputation: 4907

Selecting pairs of html elements in jquery

I'm working with some server code that is generating html that looks something like:

<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 a span but I can't figure out a way to select pairs of elements on jquery in order to use wrapAll() on them. I can't change the html that I am working with. Can anyone help?

Upvotes: 7

Views: 1640

Answers (3)

ShankarSangoli
ShankarSangoli

Reputation: 69915

You can try this.

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

Upvotes: 4

danp
danp

Reputation: 15251

$("input+label") might well be helpful.

http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors

Upvotes: 2

bjornd
bjornd

Reputation: 22951

$('input').each(function(){
    $(this).next('label').add(this).wrapAll('<span>');
});
  1. next will find the closest sibling element.
  2. add will add the matched item to the collection.

Demo

Upvotes: 13

Related Questions