I have a html structure like this:
<div class="one">
<div id="two">
<h2>Any</h2>
<h4>Any</h4>
</div>
<div id="three">
</div>
</div>
I have to select the first and the first's children elements, in the above case: #two, h2, h4, without knowing the first element's id name. How could I do that?
I can select the first element but if I add contents().find() to div:first I can't select its children:
$(document).ready(function() {
$(".one").mouseover(function () {
$(this).children('div:first').contents().find('h2,h4').stop(true, true).fadeIn('fast');
});
$(".one").mouseout(function () {
$(this).children('div:first').contents().find('h2,h4').stop(true, true).fadeOut('fast');
});
});
The final and working (no flicker!) code is:
$(".one").hover(function () {
$(this).children('div:first').stop(true, true).fadeIn('fast');
}, function() {;
$(this).children('div:first').stop(true, true).fadeOut('fast');
});
I guess I have to give myself more time to think before coming here and asking questions. Anyway, I learned about .andSelf() and the a bit of Jquery syntax. Thanks again.
You don't need to use both find()
and contents()
- Try this:
$(document).ready(function() {
$(".one").mouseover(function () {
$(this).children('div:first').children('h2,h4').stop(true, true).fadeIn('fast');
});
$(".one").mouseout(function () {
$(this).children('div:first').children('h2,h4').stop(true, true).fadeOut('fast');
});
});
And if you need to also keep the 'first' element in the nodeset, use .andSelf()
after the second .children()
(as per @Felix 's answer).
You can use children
[docs] and andSelf
[docs]:
$(".one").mouseover(function () {
$(this).children().first().children('h2, h4').andSelf()....
});
If you don't want to add the first child (the parent) to the set, omit andSelf
. Your question is a bit vague in this point. But I assume you actually don't want to select the first child, only its children. If you hide an element, its children are hidden too.
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