How to get elements of specific class starting with a given string?

后端 未结 11 852
面向向阳花
面向向阳花 2021-02-03 21:19

I have a list of elements that have multiple classes, for example:


         


        
相关标签:
11条回答
  • 2021-02-03 21:40

    How about this? http://api.jquery.com/attribute-contains-word-selector/

    $('input[class~="btn-"]')
    
    0 讨论(0)
  • 2021-02-03 21:43

    This function can get Class, ID, Data and all kind of attributes using regex

    $.fn.Get_Attr_Regex = function(Pattern,Type) 
    {
        Type = Type || 'class';
        var List_Str = this.attr(Type);
    
        if(typeof List_Str !== typeof undefined && List_Str !== false) 
        {
            var regex = new RegExp(Pattern, "g");
            var List_Array = List_Str.split(" ");
            for(var i = 0; i < List_Array.length; i++)
            {
                if(regex.test(List_Array[i]))
                {
                    return List_Array[i];
                }
            }
        }
        return false;
    };
    

    To use it

    $('.T_Header').Get_Attr_Regex('btn.*','class'); // => return class value which start with btnxxx
    

    or

    $('.T_Header').Get_Attr_Regex('btn.*','id');  // => return id value which start with btnxxx
    

    or

    $('.T_Header').Get_Attr_Regex('btn.*','data-info'); // => return data attribute value which start with btnxxx
    
    0 讨论(0)
  • 2021-02-03 21:44

    You can also try:

    $(".etape").click(function () {
        var theClass = $(this).attr("class").match(/btn[\w-]*\b/);
        console.log(theClass); 
    });
    

    Uses match instead of grep...

    0 讨论(0)
  • 2021-02-03 21:44

    You could just make btn its own class. However, this will work.

    $("div[class^='btn-']")
    
    0 讨论(0)
  • 2021-02-03 21:48

    It would probably be better to store those values in the data attribute:

    <input class="etape others" data-btntype="info">
    <input class="etape others" data-btntype="inverse">
    <input class="etape others" data-btntype="danger">
    

    Then:

     $(".etape").click(function(){
         var myBtnType = $(this).data('btntype');
     });
    

    jsFiddle

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