0

I'm trying to get the class of an element but i don't know the method that will do it. HTML:

<div class="one"></div>

jQuery:

$(document).ready(function() {
    var divclass =  // Over here
    console.log(divclass)
});

Can anyone help me? NOTE: I'm trying to log the class of the div with the class 'one'.

ooransoy
  • 785
  • 5
  • 10
  • 25
  • And why do you need the class – adeneo Dec 10 '13 at 16:08
  • @adeneo I had to toggle between three classes so i need to get the class name – ooransoy Dec 10 '13 at 16:10
  • besides - duplicate question alert! http://stackoverflow.com/questions/2400386/get-class-name-using-jquery – Biketire Dec 10 '13 at 16:12
  • @avaragecoder If you know all of the possibilities, I would recommend `$element.hasClass('.one')` or maybe `$element.is('.one')`. – Jason P Dec 10 '13 at 16:16
  • @JasonP That wouldn't work because there is 3 classes so i would need to write 3 variables, 3 if/else statements and 6 .hasClass functions, So that would not be dry. NOTE: DRY means Don't Repeat Yourself. – ooransoy Dec 11 '13 at 11:13

3 Answers3

5

Considering that the div-element is the first div-element in your html

$(document).ready(function() {
   var divclass =  $("div").attr("class"); 
   console.log(divclass)
});
Biketire
  • 2,019
  • 1
  • 23
  • 41
2

You have to select the target element first. Then you can get its class by using .attr() function. Basically .attr() will helps you to get any attributes of a particular element.

Please read here to get a full grip.

Try this,

$(document).ready(function() {
    var divclass = $('div').first().attr('class');
    console.log(divclass)
});

Here in the above code .first() is optional. I just used this to get the first element from the element collection. Please read here to know more about it.

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

You can use jquery .attr() method to retrieve class name

$(function(){
  var divclass = $("div").attr("class"); 
  console.log(divclass);
});
Krish R
  • 22,583
  • 7
  • 50
  • 59