Cream Whipped Airplane Cream Whipped Airplane - 2 months ago 10
jQuery Question

Take two elements and wrap them in a div and insert another div inside

I'm trying to wrap radio input with its label and then insert an element into the newly created wrapper, but between the input and the label, and I can't seem to find an easy way

I'd like to turn this

<fieldset data-radio-req>
<label>Choose Your Favorite</label>
<input type="radio" name="pokemon" value="Red">
<label>Red</label>
<input type="radio" name="pokemon" value="Blue">
<label>Blue</label>
<span class="form-error">This field is required.</span>
</fieldset>


Into this

<fieldset data-radio-req>
<label>Choose Your Favorite</label>
<div class="toggle-box"> <!-- wrapper -->
<input type="radio" name="pokemon" value="Red">
<span><i></i></span> <!-- newly iserted -->
<label>Red</label>
</div>
<div class="toggle-box"> <!-- wrapper -->
<input type="radio" name="pokemon" value="Blue">
<span><i></i></span> <!-- newly iserted -->
<label>Blue</label>
</div>
<span class="form-error">This field is required.</span>
</fieldset>


Currently I do

$('input[type="radio"]').each(function(index) {
$(this).next('label').andSelf().wrapAll("<div class='toggle-box'></div>");
});


But I don't know how to easily insert the
'<span><i></i></span>'
into the newly created
.toggle-box
between the
input
and the
label
without doing another
.each()

Answer

How about:

$('input[type="radio"]').each(function(index) {
    $(this).next('label').andSelf().wrapAll("<div class='toggle-box'></div>").parent().append('<span><i></i></span>');
});

Please check below snippet.

$('input[type="radio"]').each(function(index) {
  $(this).next('label').andSelf().wrapAll("<div class='toggle-box'></div>").parent().append('<span><i></i></span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset data-radio-req>
  <label>Choose Your Favorite</label>
  <input type="radio" name="pokemon" value="Red">
  <label>Red</label>
  <input type="radio" name="pokemon" value="Blue">
  <label>Blue</label>
  <span class="form-error">This field is required.</span>
</fieldset>

or if you want the span between the input and the label:

$('input[type="radio"]').each(function(index) {
  $(this).next('label').andSelf().wrapAll("<div class='toggle-box'></div>").parent().find('label').before('<span><i></i></span>');
});

  $('input[type="radio"]').each(function(index) {
  $(this).next('label').andSelf().wrapAll("<div class='toggle-box'></div>").parent().find('label').before('<span><i></i></span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset data-radio-req>
  <label>Choose Your Favorite</label>
  <input type="radio" name="pokemon" value="Red">
  <label>Red</label>
  <input type="radio" name="pokemon" value="Blue">
  <label>Blue</label>
  <span class="form-error">This field is required.</span>
</fieldset>

Comments