Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting pairs of html elements in jquery

Tags:

html

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?

like image 956
boz Avatar asked Dec 14 '11 16:12

boz


People also ask

How many types of jQuery selectors are available?

Two selectors: visible and: hidden are also available in JQuery.

How do I select a class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

Which selects all the p elements on the page?

CSS selector is selecting all p elements in page.


3 Answers

$('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

like image 148
bjornd Avatar answered Oct 27 '22 00:10

bjornd


You can try this.

$('input').each(function(){
    $(this).next().andSelf().wrapAll('<span>');
});
like image 20
ShankarSangoli Avatar answered Oct 26 '22 23:10

ShankarSangoli


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

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

like image 37
dmp Avatar answered Oct 26 '22 23:10

dmp