How to use JQuery to show a div's child elements only?

33,579

Solution 1

That's what this is for!

$(".thumb").hover(
    function() {
       $(this).children('.blurb').show();
    },
    function(){
       $(this).children('.blurb').hide();
    }
);

Solution 2

Use $(this).children() instead of executing a global query again:

$(".thumb").hover(function() {
    $(this).children().show();
}, function() {
    $(this).children().hide();
});

Working demo: http://jsfiddle.net/h5x3f/2/

Note: if you're not bothered about supporting Internet Explorer 6, you can avoid jQuery/JavaScript completely and use CSS's :hover pseudo-class, which will even work with JS disabled. Or you could use a shim like ie-7.js to handle :hover for you. See this variation of your fiddle for an example.

Solution 3

Select the div first and then its children, e.g.

$("#mydiv").children(".blurb").show();

Solution 4

here you have another solution using the 'find' function:

    $(".thumb").hover(
        function() {
            $(this).find(".blurb").show();
        }, function() {
            $(this).find(".blurb").hide();
        }

    );
Share:
33,579
raeq
Author by

raeq

Updated on March 11, 2020

Comments

  • raeq
    raeq about 4 years

    So I have this jquery function that's supposed to show a class's hidden span on hover. How do i set up the function so it only shows the selected div's child span (instead of showing all the spans on the page)?

    Here's my jquery function:

    $(".thumb").hover(
        function() {
           $(".blurb").show();
        },
        function(){
           $(".blurb").hide();
        }
    );
    

    You can view the jsfidde here. Thanks!

  • mrtsherman
    mrtsherman about 13 years
    This is a good answer. You can use a selector in children() also. So if you only wanted the first span you could do .children('span:first')
  • lindsten
    lindsten about 13 years
    If it's the div you're hovering, then you should use $(this) as suggested by the others...
  • Andy E
    Andy E about 13 years
    @mrtsherman: yeah, that's correct. However, I would advise against using a selector if you don't need to - it requires parsing and each element needs to be tested against it, so it's more of a performance hog.
  • AndrewLeonardi
    AndrewLeonardi over 7 years
    This is awesome. Thanks!