Using jQuery, how can I get the current class of a div called div1
?
Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)
jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
jQuery provides toggleClass() method to toggle an CSS class on the matched HTML element(s). Following is the syntax of the toggleClass() method: $(selector).
Just get the class attribute:
var div1Class = $('#div1').attr('class');
Example
<div id="div1" class="accordion accordion_active">
To check the above div for classes contained in it
var a = ("#div1").attr('class'); console.log(a);
console output
accordion accordion_active
Simply by
var divClass = $("#div1").attr("class")
You can do some other stuff to manipulate element's class
$("#div1").addClass("foo"); // add class 'foo' to div1 $("#div1").removeClass("foo"); // remove class 'foo' from div1 $("#div1").toggleClass("foo"); // toggle class 'foo'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With