2

I'm having following markup:

<div class="controls"> <input type="radio" id="sex" name="sex" value="m"> Boy <input type="radio" id="sex" name="sex" value="f"> Girl <input type="radio" id="sex" name="sex" value="t"> Twins </div> 

How can I select each radio button and it's subsequent text. My goal is to wrap both in a label, so the output would be:

<div class="controls"> <label><input type="radio" id="sex" name="sex" value="m"> Boy</label> <label><input type="radio" id="sex" name="sex" value="f"> Girl</label> <label><input type="radio" id="sex" name="sex" value="t"> Twins</label> </div> 

Unfortunately, the markup is created by a CMS. (It also adds id="sex" multiple times, blergh).

2
  • 7
    Sounds like you need a better CMS... Commented Oct 24, 2014 at 13:56
  • Yeah, you should never have duplicate IDs Commented Oct 24, 2014 at 14:08

1 Answer 1

6

The shortest I can think of:

$('.controls :radio').each(function() { $(this).add(this.nextSibling).wrapAll('<label>'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="controls"> <input type="radio" id="sex" name="sex" value="m"> Boy <input type="radio" id="sex" name="sex" value="f"> Girl <input type="radio" id="sex" name="sex" value="t"> Twins </div>

Sign up to request clarification or add additional context in comments.

1 Comment

That's it! Didn't know about the .add() function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.