简体   繁体   中英

Selecting range of elements with jQuery and CSS

I am trying to select a range of anchor elements using nth-child pseudo selector. The problem is that nth-child will work only with child elements, but I have a structure like this:

<div>
  <a>first link>
</div>
<div>
  <a>Second link</a>
</div>
<div>
  <a>Third link</a>
</div>

In this case, the following selector that I found useful for selecting first 2 matched elements doesn't work:

$("a:nth-child(n+1):nth-child(-n+2)")

I created an example here: http://jsfiddle.net/o6w5orom/ , in the first example all the elements are returned instead of first 2. In the second one works but only with direct children.

So, is there a way to construct CSS selector for jQuery that will basically return a range of elements, something like nth-child, but will work on matched elements of a jQuery object ? I want to construct the selector, don't wan't to write logic to process a jQuery object.

Use: $("div:nth-child(n+1):nth-child(-n+2) a")

Select the divs with the nth-child then descend to the a 's

Yes, you are right - :nth-child returns only direct children. But what's the problem? Use find.

$("div:nth-child(n+1):nth-child(-n+2)").find('a')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM