Guillermo Carone Guillermo Carone -4 years ago 159
jQuery Question

Move element before second to last h2 with jQuery

I am trying to move an elmement with class

from its native possition tu just before the second to last H2.

I am using the following which is not working:

$('.books_inarticle_list').insertBefore('#content_column > h2:nth-last-child(2)');

On the other hand something like this works:

$('.books_inarticle_list').insertBefore('#content_column > h2:nth-of-type(6)');

So the issue must be with the
selector, but I don't see what it might be.

Does anyone see anything wrong with that code or knows an alternative way to move that element to just before the second to last H2 tag?

Answer Source

Try the .get() method, which supports negative numbers to go in reverse.

$('.books_inarticle_list').insertBefore($('#content_column > h2').get(-2));

Edit On second thought, it makes more sense to follow your own examples and use the :nth-last-of-type() selector, which will go in reverse.

$('.books_inarticle_list').insertBefore('#content_column > h2:nth-last-of-type(2)');

The reason :nth-last-child() isn't working for you is because that, and :nth-child(), refers to the number of siblings they have in the DOM, not the list of elements returned by the selector.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download