Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Find first direct child of a type

I am looking for a way to find the first direct child of an element, of a precise type.

Let's imagine this markup:

<div id="mainDiv">
    <div id="otherDiv">
        <p> Stuff </p>
    </div>
    <p> Stuff 2 </p>
    <p> Stuff 3 </p>
</div>

So here, what I want to get is "Stuff 2" the first paragraph to be a direct child.

If using jquery I do something like $('#mainDiv').find('p:first'); I will get the paragraph inside the first div.

What I need is to ignore nested childs and take only the first direct one. How should I do that?

like image 861
nialna2 Avatar asked Mar 01 '14 17:03

nialna2


1 Answers

Use the direct descendant selector >

$('#mainDiv > p:first')

or even children()

$('#mainDiv').children('p').first()
like image 113
adeneo Avatar answered Oct 28 '22 13:10

adeneo