Search code examples
jquerydomjquery-selectorshtml-listsinsertafter

JQuery .insertAfter doesn't work in this example - Why?


I'm not sure why my jquery code isn't working. I'm creating a Wordpress theme for my company to use, and I can't seem to get the .insertAfter() function working correctly. It just deletes all the content on the page.

<div class='entry'>
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
</div>

JQuery Section:

$('.entry:first-child').insertAfter($('.entry:last-child'));

Any ideas?


Solution

  • Your .entry:first-child is selecting the div itself, when I imagine it should be selecting the first ul. So you are currently trying to insert an element after itself, which doesn't work.

    console.log($('.entry:first-child')[0] == $('.entry:last-child')[0]); // true
    

    Try this...

    $('.entry ul:first-child').insertAfter('.entry ul:last-child');
    

    jsFiddle.

    You can also see you can just pass the selector string to insertAfter, you do not need to wrap it again with $().