matthewb
matthewb

Reputation: 864

add class to a element if the parent element contains an element

i have to add a class to a element(h2) on it's click event if the parent element(class="container") contains an element(class="sub-cat") inside it. fiddle link

$('.container h2').click(function(){
//alert('hi');
if($(this).has(".sub-cat")){
    $('.container h2').addClass(highlight);
}
else if () {
    $('.container h2').removeClass(highlight);
}

});

Upvotes: 2

Views: 213

Answers (3)

aguynamedloren
aguynamedloren

Reputation: 2273

$('.container h2').click(function(){
    if ($(this).closest('.container').find('.sub-cat').length) {
        $(this).addClass('highlight');
    } else {
        $(this).removeClass('highlight');
    }
});​

When the h2 element is clicked, use closest() to traverse up through the DOM tree and find the first parent element with class 'container', then use find() to traverse back down the DOM to find the element with class 'sub-cat'. If the '.sub-cat' element is found (length), add 'highlight' class to the clicked h2, otherwise, remove 'highlight' class from the clicked h2.

jQuery docs for Tree Traversal

Upvotes: 1

voigtan
voigtan

Reputation: 9031

when you use click then this referce to the h2 you clicked on, use .parent() to (or .closest('.container') and then use your look up:

http://jsfiddle.net/gSCQ7/7/

var highlight = "highlight";

$('.container h2').click(function(){
    var hasSubCategorys = $(this).parent().find(".sub-cat").length > 0;
    $(this)[hasSubCategorys  ? 'addClass' : 'removeClass'](highlight);
});

or if you want it more readable:

var highlight = "highlight";

$('.container h2').click(function(){
    var hasSubCategorys = $(this).parent().find(".sub-cat").length > 0;
    if(hasSubCategorys) {
        $(this).addClass(highlight);
    } else {
        $(this).removeClass(highlight);
    }
});

edit: http://jsfiddle.net/gSCQ7/10/ changed the CSS code to be more specific then .container h2 vs .hightlight

Upvotes: 4

V1tOr
V1tOr

Reputation: 369

try

if( $(this).parent().find(".sub-cat").length > 0 ) {
  ...
}

or

if( $(this).closest(".container").find(".sub-cat").length > 0 ) {
  ...
}

Upvotes: 0

Related Questions