Know which div contains a specific class in jquery/javascript

Asked

Viewed 595 times

1

I need to know the amount of Ivs that contain a specific class, I thought I’d search all the css I have on Ivs, so I’ll eliminate until I find the Ivs with "has-error", only I can’t find out who exactly has the "has-error" class"

How to do?

$(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 to brand solved for two people at once? hhaha Thanks to all

  • I don’t know if I understood it very well, but it wouldn’t be simpler to use the Class Selector? It would look something like this: $('div.has-error')... You could also remove the div and leave only the class.

  • I believe so, but I do not know how to implement, as would be in my code?

  • 1

    var numItems = $('.item'). length;

  • thanks man, thank you

2 answers

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>

<div class="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>

  • +1 for the funssional example. : D

  • @Wrong spelling dvd is fumssional with M, the n only precedes

  • That thing with $("#div1", "#div2") means: search #div1 inside #div2... now $("#div1, #div2") means selecting the two ids.

  • All right, I’ll get an app #div1 dentro de #div2 that I’ve never seen

1


You can do it in a simple way with jQuery:

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

In the above case you will find only divs with the class. To count any, use:

$(".has-error").length

In your code, you’d be:

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

With pure Javascript:

var erros = document.body.querySelectorAll("div.has-error").length;
  • kkkk, the same

  • @Leocaracciolo mine is canonical rs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.