Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

jquery

This is my code and i want to enclose each 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>
like image 890
Ashok Khot Avatar asked Oct 03 '17 07:10

Ashok Khot


3 Answers

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>
like image 68
Shadow Fiend Avatar answered Nov 14 '22 20:11

Shadow Fiend


You can use .map()

$('input').map(function(index){
  $(this).next().andSelf().wrapAll('<div>');
});

Demo

$('input').map(function(index){
  $(this).next().andSelf().wrapAll('<div>');
});
<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>
like image 45
Carsten Løvbo Andersen Avatar answered Nov 14 '22 20:11

Carsten Løvbo Andersen


Associate both input and label with map and select both of the specific elements and wrap them up:

$('input').map(function() {
  $(this).next().addBack().wrapAll('<div>');
});

JsFiddle

Updated with .addBack() since .addSelf() is deprecated

like image 41
urbz Avatar answered Nov 14 '22 21:11

urbz