Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first child's children with Jquery

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.

like image 538
elbatron Avatar asked Dec 21 '22 10:12

elbatron


2 Answers

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).

like image 143
irama Avatar answered Dec 28 '22 08:12

irama


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.

like image 43
Felix Kling Avatar answered Dec 28 '22 10:12

Felix Kling