Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery change the Element Order

Tags:

html

jquery

How can I move each label in front of the input element they're next to using jQuery?

<div class="input select classCheckBox">
    <label for="checkboxId">classCheckBoxs</label>
    <input type="hidden" id="checkboxId" value="" name="checkboxName" />
    <br /> 
    <div class="classCheckBox"> 
        <input type="checkbox" id="checkboxId24" value="1" name="checkboxName[]" />
        <label for="checkboxId24">1 </label>
    </div>
    <div class="classCheckBox">
        <input type="checkbox" id="checkboxId25" value="2" name="checkboxName[]" />
        <label for="checkboxId25">2</label>
    </div>
    <div class="classCheckBox"> 
        <input type="checkbox" id="checkboxId26" value="3" name="checkboxName[]" />
        <label for="checkboxId26">3</label>
    </div>
    <div class="classCheckBox">
        <input type="checkbox" id="checkboxId27" value="4" name="checkboxName[]" />
        <label for="checkboxId27">4</label>
    </div>
    <div class="classCheckBox"> 
        <input type="checkbox" id="checkboxId28" value="5" name="checkboxName[]" />
        <label for="checkboxId28">5</label>
    </div>
</div>
like image 584
MuntingInsekto Avatar asked Jun 25 '12 04:06

MuntingInsekto


People also ask

How to change order of element in jQuery?

To change order of divs with jQuery, we can use the insertAfter method. to add 3 divs. Then we take the first div and insert it after the 3rd with: const tests = $('.

How to replaceWith in jQuery?

The replaceWith() method in jQuery is used to replace the selected elements with the new one. This method replaces the matched elements with the specified HTML elements. It returns the replaced elements. This method is similar to the replaceAll() method.

How do you change a div?

If you need to completely replace the HTML content of the div , use the innerHTML property. Copied! const div = document. getElementById('container'); // ✅ Change (replace) the text with HTML div.


1 Answers

$('.select .classCheckBox label').each(function() {
  $(this).insertBefore( $(this).prev('input') );
});

DEMO


A little explain

  • $('.select .classCheckBox label') select each label within each .classCheckBox

  • $(this) within loop point to label

  • .insertBefore() insert any element before the matched element that passed as argument

  • $(this).prev('input') points the input before label

  • so, $(this).insertBefore( $(this).prev('input') ) will insert each label before its previous input


Related refs:

  • .insertBefore()

  • .prev()

  • .each()


Alternate ways:

$('.select .classCheckBox input').each(function() {
  $(this).insertAfter( $(this).next('label') );
});

DEMO

OR

$('.select .classCheckBox input').each(function() {
  $(this).before( $(this).next('label') );
});

DEMO

like image 135
thecodeparadox Avatar answered Sep 27 '22 19:09

thecodeparadox