Jquery - check if parent contains element with class

I had a problem trying to figure out if the parent element has an element with a specific class:

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

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

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

// do something

}

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

+3
source share
1 answer

.has does not 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>
+3
source

Source: https://habr.com/ru/post/1759291/


All Articles