Test Jquery classes

Asked

Viewed 407 times

3

I know that to test if an element has a class we use hasClass(), but my question is as follows. I have an element with a class and assign a second class to it with classToggle(). Is there a way to test whether a class has another class? If you got confused I’ll be answering and editing everything.

1 answer

4


I don’t know if this fully answers your question, but you can retrieve the classes as follows.

Example:

HTML

<div id="minhaDiv" class="classe1 classe2 classe3"></div>

JS

var classes = document.getElementById("minhaDiv").className.split(' ');
console.log(classes);

or

Jquery

var classes = $("#minhaDiv").attr("class").split(' ');
console.log(classes);

The variable will be populated with a Array containing all classes that are set in the element.

Result (Console)

["Classe1", "classe2", "classe3"]

DEMO - Example

And if the browser supports the element.classList, just make this way that the resutaldo will be the same.

Example 2:

JS

var classes = document.getElementById("minhaDiv").classList;
console.log(classes);

DEMO - Example 2

Browser other questions tagged

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