Reputation: 1194
Here is the fiddle: http://jsfiddle.net/Xhqz9/
I'm trying to find all images inside <div id="primary" />
except the images located inside any <div class="nohover" />
, which is always a child element, and do a hover effect on those images.
<div id="primary">
<img src="http://placehold.it/75x75">
<div class="nohover">
<img src="http://placehold.it/75x75">
</div>
<img src="http://placehold.it/75x75">
<div class="nohover">
<img src="http://placehold.it/75x75">
</div>
</div>
jQuery:
var postImgsRed = $('#primary').find('img');
postImgsRed.each(function() {
$(this).css('border', '1px solid red');
});
var postImgsHover = $("#primary > :not(.nohover)").find("img");
postImgsHover.each(function() {
$(this).hover(function() {
$(this).fadeOut(100);
$(this).fadeIn(500);
})
});
My hover function is not executing correctly. it won't do the effect on the 1st or 3rd image, as I want to do. What am I doing wrong?
Upvotes: 1
Views: 146
Reputation: 8210
var postImgsRed = $('#primary').find('img');
postImgsRed.each(function() {
$(this).css('border', '1px solid red');
});
var postImgsHover = $("#primary > img");
postImgsHover.each(function() {
$(this).hover(function() {
$(this).fadeOut(100);
$(this).fadeIn(500);
})
});
Fiddle: http://jsfiddle.net/Xhqz9/1/
Note: This works for your example. You need to change it up if you can have images that aren't direct descendants of #primary
match the condition with $("#primary img").not(".nohover img")
.
Upvotes: 2
Reputation: 33661
Use the .not selector and filter out the ones under .nohover
$('#primary img').not('.nohover img')
Fiddle with your hover effects
Upvotes: 2
Reputation: 4751
Use .not() to exclude elements with the .nohover class:
$('#primary div').not('div.nohover').find('img')...
Upvotes: -1
Reputation: 25652
Use children()
instead of find()
as it will only select the direct descendants of your node instead of any descendants : http://api.jquery.com/children/
$('#primary').children('img');
Upvotes: 0
Reputation: 53246
You can just find direct img
descendents of #primary
:
$('#primary > img').each();
Upvotes: 0