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 .insert开发者_开发知识库After() 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?
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 $()
.
This should work:
$('.entry ul:first-child').insertAfter($('.entry ul:last-child'));
http://jsbin.com/ihihi4/5
As Alex pointed out, you could have used another selector in the .insertAfter call instead of a jquery object.
The jquery documentation is great for explaining this:
http://api.jquery.com/insertAfter/
Of note is the subtle difference between insertAfter and after.
http://api.jquery.com/after
The same applies to insertBefore / before and appendTo and append. It's useful to understand the differences.
It's confusingly-named, as it's not "find the element with the class 'entry' and then select its first child." The jQuery documentation says, "[First-child] selects all elements that are [themselves] the first child of their parent." Which in this case is your div.entry.
精彩评论