14

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>

1 Answer 1

25
$('.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:


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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.