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

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

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


         


        
11条回答
  •  庸人自扰
    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
    

提交回复
热议问题