Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the current class of a div with jQuery?

Tags:

jquery

Using jQuery, how can I get the current class of a div called div1?

like image 279
Shyju Avatar asked Oct 08 '09 07:10

Shyju


People also ask

How can I get the current displayed div id in jQuery?

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.

How do I select a div class?

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 (.)

How check class is present or not in jQuery?

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".

Can you access a CSS class from jQuery?

jQuery provides toggleClass() method to toggle an CSS class on the matched HTML element(s). Following is the syntax of the toggleClass() method: $(selector).


2 Answers

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 
like image 72
Christian C. Salvadó Avatar answered Oct 01 '22 05:10

Christian C. Salvadó


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' 
like image 21
Jakub Arnold Avatar answered Oct 01 '22 04:10

Jakub Arnold