Ashok Khot Ashok Khot - 1 year ago 121
jQuery Question

how to wrap each input and label in one div using jquery

This is my code and i want to enclose each input and label with div



<div>
<input type="checkbox" name="checkbox1">
<label for="checkbox1">checkbox1</label>
<input type="checkbox" name="checkbox2">
<label for="checkbox2">checkbox2</label>
<input type="checkbox" name="checkbox3">
<label div="checkbox3">checkbox3</label>
<input type="checkbox" name="checkbox4">
<label for="checkbox4">checkbox4</label>
</div>





and, i want to enclose each input and label with div like



<div>
<div>
<input type="checkbox" name="checkbox1">
<label for="checkbox1">checkbox1</label>
</div>
<div>
<input type="checkbox" name="checkbox2">
<label for="checkbox2">checkbox2</label>
</div>
<div>
<input type="checkbox" name="checkbox3">
<label div="checkbox3">checkbox3</label>
</div>
<div>
<input type="checkbox" name="checkbox4">
<label for="checkbox4">checkbox4</label>
</div>
</div>




Answer Source

Try this

$('input').each(function() {
  $(this).next('label').andSelf().wrapAll('<div class="testing"/>');
});
.testing {
  background-color: blue;
}

.testing>label {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="checkbox" name="checkbox1">
  <label for="checkbox1">checkbox1</label>
  <input type="checkbox" name="checkbox2">
  <label for="checkbox2">checkbox2</label>
  <input type="checkbox" name="checkbox3">
  <label div="checkbox3">checkbox3</label>
  <input type="checkbox" name="checkbox4">
  <label for="checkbox4">checkbox4</label>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download