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

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

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

相关标签:
11条回答
  • 2020-12-03 01:02
    var className=$('selector').attr('class');
    

    or

    var className=$(this).attr('class');
    

    the classname of the current element

    0 讨论(0)
  • 2020-12-03 01:05
    var classname=$('#div1').attr('class')
    
    0 讨论(0)
  • 2020-12-03 01:06

    The addClass method in jQuery has a currentClass built in property. You can use it inside a function call. Like so:

    <div>First div</div>
    <div class="red">Second div</div>
    <div>Third div</div>
    <div>Fourth div</div>
    
    <script>
      $("div").addClass(function(index, currentClass) {
        var addedClass;
        if ( currentClass === "red" ) {
          addedClass = "green"; }
        return addedClass;
      });
    </script>
    
    0 讨论(0)
  • 2020-12-03 01:09

    if you want to look for a div that has more than 1 class try this:

    Html:

    <div class="class1 class2 class3" id="myDiv">
    

    Jquery:

    var check = $( "#myDiv" ).hasClass( "class2" ).toString();
    

    ouput:

    true

    0 讨论(0)
  • 2020-12-03 01:11
    <div  id="my_id" class="my_class"></div>
    

    if that is the first div then address it like so:

    document.write("div CSS class: " + document.getElementsByTagName('div')[0].className);
    

    alternatively do this:

    document.write("alternative way: " + document.getElementById('my_id').className);
    

    It yields the following results:

    div CSS class: my_class
    alternative way: my_class
    
    0 讨论(0)
提交回复
热议问题