Inzamam Tahir
Inzamam Tahir

Reputation: 537

jquery nth-child() not working

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

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196306

I see two problems

  1. there are some hidden characters in the script in your question (perhaps it is just the copy/paste)
  2. you need to target the 5 element in the 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

John Flatness
John Flatness

Reputation: 33829

Quoting jQuery:

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

Related Questions