How to use JQuery to show a div's child elements only?
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();
}
);
raeq
Updated on March 11, 2020Comments
-
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 about 13 yearsThis 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 about 13 yearsIf it's the div you're hovering, then you should use
$(this)
as suggested by the others... -
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 over 7 yearsThis is awesome. Thanks!