Reputation: 49
we have
<div class="grandparent">
<div class="parent"><a href="#">a</a></div>
<div class="parent"><a href="#">b</a></div>
<div class="parent"><a href="#">c</a></div>
</div>
on hover over any link i want to test if 'parent' is first-child of 'grandparent' if not i want to apply a class
this is just a simplified example i don't have class names in the element parent and grandparent
Upvotes: 1
Views: 2832
Reputation: 208032
Compare the elements with:
$('div > a').mouseover(function () {
if ($(this).parent()[0] !== $('div > div:first')[0]) $(this).addClass('special')
})
Or:
$('div > a').mouseover(function () {
if (!$(this).parent().is($('div > div:first'))) $(this).addClass('special')
})
Upvotes: 0
Reputation: 846
$('.grandparent > div').hover(function() {
// If the child is NOT the first
if (!$(this).is('div:first-child')) {
$(this).addClass('not-first');
}
});
Note: You will have to adjust this solution to suit your specific DOM elements since you aren't using classnames.
Upvotes: 1
Reputation: 318352
If you just need to set styles you can do this with CSS and the adjacent sibling selector (CSS3)
.grandparent .parent:first-child ~ .parent:hover a {
color: red;
}
Upvotes: 1
Reputation: 2044
(function(){
$("div.grandparent div.parent:not(:first-child)").on('mouseover', function(){
$(this).addClass("classHere");
console.log($(this));
});
})();
Upvotes: 0
Reputation: 4414
Would probably do it like so:
var $parents = $(".parent"); // cache parents
$("a").hover(function(){
// mouse enters link
var $par = $(this).parent();
if($parents.index($par) !== 0){
$(this).addClass("not-first");
}
}, function(){
// mouse leaves link
$(this).removeClass("not-first");
});
Upvotes: 0
Reputation: 540
You can use the .not and the :first-child of jquery.. http://jsfiddle.net/7wLtY/
$('.parent').not(':first-child').hover(function() {
$( this ).addClass( "not-first-child" );
}, function() {
$( this ).removeClass( "not-first-child" );
});
Upvotes: 0
Reputation: 1547
$(document).on('mouseenter','a',function(){
if($(this).parent().is(':first-child')){
alert('my parent is first child');
} else {
$(this).addClass('myParentIsNot');
}
});
Fiddle:
Upvotes: 6
Reputation: 994
Use jQuery's .index() to test where it falls below grandparent.
$("div.grandparent").on("mouseenter", "div.parent", function(e) {
if($(this).parent(".grandparent").children("div.parent").index(this) > 0) {
$(this).addClass("not-the-first");
}
});
Upvotes: 0