dev_willis
dev_willis

Reputation: 580

How can I use jQuery to match nth-child or last if nth not found?

I need to be able to insert some markup into a document after() the second P element in a container. If there is only one element then I need to insert after() that one. nth-child simply does not make a match if there is only one element. How can I do this? Thanks!

Upvotes: 2

Views: 83

Answers (1)

cookie monster
cookie monster

Reputation: 10972

Select them both, and grab the first match.

$("#foo > p:nth-child(2), #foo > p:lastChild").eq(0).append(...;

Because the results are returned in document order, you can use the 0 index to get the nth-child or if it wasn't there, it'll get the last child.


If there are other element types, and you only care about the p elements, then use nth-of-type instead.

$("#foo > p:nth-of-type(2), #foo > p:lastChild").eq(0).append(...;

Upvotes: 5

Related Questions