JQuery: Find the first two children

Using jQuery, what is the most efficient way to find the first two children of a parent if one is h1 and the other is p . My code is not working right now, and I would like to do it 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 work with several divs. I did not think that it would matter, but it looks like I was wrong.

+7
source share
9 answers

Try

 $('div').children().slice(0,2).show(); 

If you have more than 1 div, try as below,

 $('div').each (function () { $(this).children().slice(0,2).show(); }); 
+19
source

alternative slice() method:

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

(but I also recommend cutting, especially for large collections)

+4
source
 $('div').children().slice(0, 2).show(); 
+1
source

You can use less than as below

 $('div > *:lt(2)').show(); 

Working violin

+1
source

Descriptive selector will

 $('div').find('h1:first, p:first').show(); 

This makes it clear what your intentions are and what elements you choose.

+1
source

http://jsfiddle.net/94EU7/

 $('div :lt(2)').show(); 
+1
source
 $('div p:first-child,div p:nth-child(2)').show(); 
+1
source

I think you need an eq() function, for example:

 $("div").children().eq(0); // first child $("div").children().eq(1); // second child 
0
source

Not sure why you need to use jQuery for this.

 var firstChild = div.firstChild; firstChild.style.display = 'initial'; firstChild.nextSibling.style.display = 'initial'; 
0
source

All Articles