Get first and last class with jQuery

后端 未结 7 1306
一整个雨季
一整个雨季 2021-02-09 02:58

Might be a newbie question. I have a code line like this:

I need to get each class for itself.

相关标签:
7条回答
  • 2021-02-09 03:35
    var classes = $(this).attr("class").split(/\s/);
    
    classes[0] === 'template'
    classes[1] === 'active'
    

    If there are more than two classnames and you only want to get the first & last (that was your question) you can call:

    classes[0] = first class
    classes[classes.length -1] = last class
    
    0 讨论(0)
  • 2021-02-09 03:38
    var class= $(this).attr("class").split(" ").pop();
    
    0 讨论(0)
  • 2021-02-09 03:38
    var class= $(this).attr("class").split(" ")  
    (for i in class)
    { alert(class[i])}
    
    0 讨论(0)
  • 2021-02-09 03:44

    If you're checking to see if a HTML element has a class, you can use .hasClass('classname') which would return true or false.

    Otherwise, if you're trying to see a list, I think you'll have split the string into an array. The other two answers that were just posted will show you how. :)

    0 讨论(0)
  • 2021-02-09 03:45

    I think that this is the easy way.

    $(".element").last().addClass("highlight");
    
    0 讨论(0)
  • 2021-02-09 03:49

    You can do this way too using map:-

    var ArrayData = $.map($(this).attr("class").split(' '), function(value){
        return value;
    });
    
    alert("first class = '"+ArrayData[0]+"'");
    alert("last class = '"+ArrayData[ArrayData.length - 1]+"'");
    

    Refer LIVE DEMO

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