Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
314 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...