beliy333
beliy333

Reputation: 479

jQuery - Traversing the dom and selecting

I'm having a hard time selecting all of the first div elements inside a parent div which appears multiple times.

For Example I need to select the first div inside every parent div that have a class of "nav". See below to understand:

<div class="container">
    <div class="nav">
        <div class="sub-item"></div> **SELECT THIS**
        <div class="sub-item"></div>
    </div>
</div>

<div class="container">
    <div class="nav">
        <div class="sub-item"></div> **SELECT THIS**
        <div class="sub-item"></div>
    </div>
</div>

I tried this code but it only selects the div in the first parent div.

$('.nav > div').eq(0);

Any help is appreciated!

Upvotes: 0

Views: 48

Answers (2)

zzzzBov
zzzzBov

Reputation: 179046

Use the :first-child selector:

$('.nav > div:first-child')

This will select every div which is the first child of a .nav element. If you don't need to select div elements specifically, you could shorten it to:

$('.nav > :first-child')

Upvotes: 1

Emre Erkan
Emre Erkan

Reputation: 8482

Just use the :first-child selector;

$('.nav > div:first-child');

Here is a jsFiddle example.

Upvotes: 3

Related Questions