Search code examples
jquerychildren

jquery index first-line children


I want to get the n-th first level child of a parent. For example, when I have dom like this:

<div id='myDiv'>
    <p>first paragraph</p>
    <p>second paragraph<span>something here</span></p>
    <p>third paragraph</p>
</div>

and use eq(), like here:

alert($('#myDiv').children().eq(2).html());

I get 'something here', but 'third paragraph' is what I need, because 'something here' is the second generation child of myDiv and should not be taken into account. I know I would use '>' selector, but I have to write a versatile script, which could work not only with 'p' children, but also 'a', 'li', 'whatever'. Hope you understand what I mean. Thanks in advance for help

UPDATE

You are right - there is nothing wrong with my js code. But, as you suggested, I have looked into my html, and saw something strange happening there. I have:

    <div>
<div><span>Option1</span> <span>Option2</span> <span>Option3</span> <span>Option4</span></div>
<div><p>Container1</p> <p><div>abc</div></p> <p>Container3</p> <p>Container4</p></div>
</div>

and what I see in elements field in browser:

<div>
<div><span>Option1</span> <span>Option2</span> <span>Option3</span> <span>Option4</span></div>
<div><p>Container1</p> <p></p><div>abc</div><p></p> <p>Container3</p> <p>Container4</p></div>
</div>

Why the paragraph is being closed before the div, and opened again after?


Solution

  • Why the paragraph is being closed before the div, and opened again after?

    Because a paragraph cannot contain a div element (to be more precise, I think a paragraph cannot contain a block element). The browser corrects your invalid(!) markup by closing the paragraph before the div.