Check if it is the class

Asked

Viewed 197 times

4

How do I check with Javascript if it’s really that class in CSS? Example:

if(é a class) {

}

or another example, if it is not the class

if(!.minhaClasse) {

}

Is there any way to do this, with pure Javascript?

  • What class would that be? Your question didn’t make much sense.

2 answers

6

With pure javascript you can do so:

<div id="teste" class="teste2"> Teste </div>
<script>
    var div = document.getElementById('teste');
    console.log(div.classList.contains('teste2'));
</script>

for more information follow link

4


You can do it like this:

function contemClasse(elemento, classe) {
    for (int i = 0; i < elemento.classList.length; i++) {
        if (elemento.classList[i] == classe) {
            return true;
        }
    }
    return false;
}

And to use:

contemClasse(foo, "nomeDaClasse");
  • 1

    I only want with pure Javascript because I’m studying, Renan. It’s not for any use.

  • 2

    @Lucascarvalho then I withdraw what I said. In that case it is good to know how things are done.

  • Okay, thanks for the answer!

  • @Renan agree with what he had said. + 1 in his reply

  • Lucas, I apologize for my aggression yesterday. Today I was reviewing my favorites here in the browser and found a site that might be interesting for you. You Might not need jQuery. It shows several of jQuery’s major features, side by side with pure Javascript code that does exactly the same thing.

Browser other questions tagged

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