简体   繁体   中英

Add class to parent that has a specific child

I want to add the class .hidden to the parent when I click on a .input class when the parent of that .input class has a child .delete . Otherwise, remove the parent instead of just hiding it. The problem is that it always adds the .hidden class to the parent, no matter what.

HTML:

<div class='container'>
    <input class='input' type='text'>
    <input class='input delete' type='text'>
</div>
<div class='container'>
    <input class='input' type='text'>
</div>

JS:

$('.input').on('click', function() {

    var element = $(this);

    if (element.parent().has('.delete')) {
            element.parent().addClass('hidden');
        } else {
            element.parent().remove();
    }
});

In your specific case

   element.parent().has('.delete')

returns a jQuery object which will have have either one or zero DOM elements in it. Used in an 'if' statement this will evaluate to true, thus you will never get the else case.

Instead use

   element.parent().has('.delete').length

which will return 0 or 1. The zero will evaluate to false in an if statement.

.has() doesn't return true/false, it selects. Change the if to:

if (element.parent().has('.delete').length) {

jsFiddle example

If you need to check if the parent has a child element with the .delete class, then you can to change your code to this:

$('.input').on('click', function() {

    var element = $(this);

    if (element.parent().children('.delete').length > 0) {
            element.parent().addClass('hidden');
        } else {
            element.parent().remove();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM