Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Find first two children

Using jQuery, what would be the most efficient way to find the first two children of a parent element, if one is an h1 and the other is a p. My code isn't working right now, and I would like to accomplish this using best practices.

CSS

div > *{
    display: none;
}

HTML

<div>
    <h1>Heading</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</div>

<div>
    <h1>Heading</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</div>

Javascript

$('div h1').show();    
$('div p:first-child').show();

Edit I'm actually working with multiple DIVs. I didn't think it would make a difference, but it looks like I was wrong.

like image 998
colindunn Avatar asked May 18 '12 20:05

colindunn


People also ask

How to select nth child in jQuery?

jQuery | :nth-child() Selector jQuery :nth-child() Selector Selects all elements that are the nth-child of their parent. even: even number of child elements get selected. odd: odd number of child elements will get selected.

Is first child jQuery?

It is a jQuery Selector used to select every element that is the first child of its parent. Return Value: It selects and returns the first child element of its parent.

What is EQ jQuery?

The eq() method returns an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 (not 1).


1 Answers

an alternative way to slice() method:

$('div').children(':lt(2)').show()

(but I recommend the slice too, especially for large collections)

like image 174
Fabrizio Calderan Avatar answered Oct 06 '22 08:10

Fabrizio Calderan