Knowing which div contains a specific class in jquery / javascript

1

I need to know the amount of divs that contain a specific class, I thought of looking for all the css I have in the divs, so I'll eliminate it until I find the divs with "has-error", but I can not find who exactly has it a class "has-error"

How to do it?

$(document).on('click', "#btnSalvar", function () {

    var erros = 0;
    $("div").find('*').each(function () {
        var classe = $(this).attr("class");
        if (classe !== undefined) {
            if ($("" + classe + ":contains(has-error)")) {

            }

        }
   });
});

What I've done so far.

Edit:

How do I fix it for two people at the same time? hhaha Thanks everyone

    
asked by anonymous 03.05.2018 / 19:37

2 answers

2

You can do it in a simple way with jQuery:

$("div.has-error").length

In the above case you will find only div s with the class. To tell any, use:

$(".has-error").length

In your code, it would look like:

$(document).on('click', "#btnSalvar", function () {
    var erros = $("div.has-error").length;
});

With pure JavaScript:

var erros = document.body.querySelectorAll("div.has-error").length;
    
03.05.2018 / 19:42
2

You can use the jquery property .length

var numItems = $('.has-error').length;

console.log (numItems);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="wrapper">
    <div class="has-error"></div>
    <div class="has-error"></div>
    <div class="has-error"></div>
    <div class="has-error"></div>
    <div class="has-error"></div>
    <div class="no-has-error"></div>
    <div class="no-has-error"></div>
</div>
    
03.05.2018 / 19:44