I know this is a really strange title, but I’ll do my best to explain the problem below:
I have a page with a layout similar to the following:
.item
pre
code
pre
code
.item
.item
pre
code
I want to select the code items (because I want to loop through them with 'each()'). However, I want to only select the first 'pre/code' combo in each .item block.
How can I do this?
At first I had $(".item pre code"), which selects all of the 'pre/code' combos. I noticed in the jQuery docs that there’s a :first-child selector. I tried sticking it on the end of the pre, but that didn’t work.
You need to use the
nth-childselector. This chooses the element that matches the argument (a 1-based index) for each of the parent selectors. (:firstonly returns the firstpre;nth-childreturns allpres that are the first child of their parent:http://jsfiddle.net/syLMD/
NB that this is equivalent to
.item pre:first-child code. As far as I can tell, that works just fine.OK, with the knowledge that the first
premay not contain acode… You can’t do this with a simple selector. This needs more complex filtering:See example. Note that this isn’t exactly going to have wonderful performance…