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()andcontents()– Try this:And if you need to also keep the ‘first’ element in the nodeset, use
.andSelf()after the second.children()(as per @Felix ‘s answer).