user398341
user398341

Reputation: 6577

jquery - check if parent does not contain element with the class

I'm having a problem with trying to find out whether the parent element does not have the element with the specific class like so:

// after clicking on the button inside of the form - get the instance of the parent form

var par = $(this).parent('form');

if(!par.has('warn')) {

// do something

}

Any idea how to achievie it - as has() doesn't seem to find it

Upvotes: 3

Views: 4384

Answers (1)

Jonathan
Jonathan

Reputation: 5993

.has doesn't return a boolean, so if there are no matches the returned object has 0 members.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
    <form>
        <div><input id="thebutton" type="button" value="Click Me" /></div>
        <div class="test">test div</div>
    </form>
<script>

$(document).ready(function() {
    $('#thebutton').click(function() {
        var par = $(this).parent('form');
        if(par.has('.warn').length === 0) {
            // do something
            alert('nothing');
        }
    });
});

</script>

</body>
</html>

Upvotes: 3

Related Questions