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.
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.
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.
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).
an alternative way to slice()
method:
$('div').children(':lt(2)').show()
(but I recommend the slice too, especially for large collections)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With