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

后端 未结 11 421
挽巷
挽巷 2020-12-03 00:19

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

相关标签:
11条回答
  • 2020-12-03 00:45

    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
    
    0 讨论(0)
  • 2020-12-03 00:45
    $('#div1').attr('class')
    

    will return a string of the classes. Turn it into an array of class names

    var classNames = $('#div1').attr('class').split(' ');
    
    0 讨论(0)
  • 2020-12-03 00:50

    From now on is better to use the .prop() function instead of the .attr() one.

    Here the jQuery documentation:

    As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

    var div1Class = $('#div1').prop('class');
    
    0 讨论(0)
  • 2020-12-03 00:51

    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'
    
    0 讨论(0)
  • 2020-12-03 00:56
    $("#div1").attr("class")
    
    0 讨论(0)
  • 2020-12-03 00:56

    try this

    $("#div1").attr("class")

    0 讨论(0)
提交回复
热议问题