sojutyp sojutyp - 4 years ago 136
jQuery Question

Different ways to select class elements

I am looking for all the possibilities to select elements of a class in jQuery.

<div class="wrap">
<div class="wrap">
<div class="wrap">


I know I can select the first and the last element by using:

$('div.wrap:first').
$('div.wrap:last').


[0], [1]
doesn't seem to work in jQuery or I am doing it wrong. Is there any other possibily to select the elements (not the first and last one)?

Answer Source

Refer to CSS Selectors.

$("div.wrap:first-child") and $("div.wrap:last-child") for first and last.

$("div.wrap:nth-child(4)") for the 4th element

$("div.wrap:even") for even elements (2nd, 4th, 6th, etc)

$("div.wrap:nth-child(4n+1)") for (4n+1)-th elements (1st, 5th, 9th, etc)

$("div.wrap:not(:first-child):not(:last-child)") for not-first, not-last element.

And so on :)

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