Reputation: 537
I need some help regarding jquery. This is HTML code
<div id="outerDiv">
<div id="firstInnerDiv">
First Inner Div
</div>
<label class="label1">First Label</label><br/>
<div id="secondInnerDiv">
Second Inner Div
</div>
<label class="label2">Second Label</label>
</div>
<label class="label2">Third Label</label>
and this is jquery code
$("#outerDiv div:nth-child(1)").insertAfter("label:nth-child(4)");
$("#outerDiv label:nth-child(1)").insertAfter("div:nth-child(4)");
The output of the above code is :
First Inner Div
First Label
Second Inner Div
Second Label
Third Label
I want a new sequence which should be like this :
Second Inner Div
Second Label
First Inner Div
First Label
Third Label
Upvotes: 0
Views: 2275
Reputation: 196306
I see two problems
insertAfter
since there is a <br>
that also counts$("#outerDiv div:nth-child(1)").insertAfter('label:nth-child(5)');
$("#outerDiv label:nth-child(1)").insertAfter('div:nth-child(5)');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="outerDiv">
<div id="firstInnerDiv">First Inner Div</div>
<label class="label1">First Label</label>
<br/>
<div id="secondInnerDiv">Second Inner Div</div>
<label class="label2">Second Label</label>
</div>
<label class="label2">Third Label</label>
Upvotes: 0
Reputation: 33829
The
:nth-child(n)
pseudo-class is easily confused with:eq(n)
, even though the two can result in dramatically different matched elements. With:nth-child(n)
, all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class.
So, when you use a selector like label:nth-child(1)
, you're saying "all label
elements that are the first child of their parent," not "all the first label
elements." If there's something else, like a div
, that's the first child, label:nth-child(1)
matches nothing.
It may be more natural for you to use .eq()
, which lets you specify an index in the matched set. Or, you could use :nth-of-type
, which works closer to how I think you assumed :nth-child
did.
Upvotes: 4