how do I find elements that contain a data-* attribute matching a prefix using jquery

前端 未结 1 661
感动是毒
感动是毒 2020-12-15 07:51

I\'m want to create a selector to find elements which have attributes starting with a string. At this point, I\'m assuming this selector does not exist. Do I need to extend

1条回答
  •  囚心锁ツ
    2020-12-15 08:20

    Well, I guess I'm reading your question differently.

    The way I read it, you want to create a custom selector that selects elements that have a given attribute name (or the start of that name).

    If so, I think you'd need to iterate of the attributes collection for each element.

    DEMO: http://jsfiddle.net/GgmM7/

    $.extend($.expr[':'],{
        attrNameStart: function(el,i,props) {
    
            var hasAttribute = false;
    
            $.each( el.attributes, function(i,attr) {
                if( attr.name.indexOf( props[3] ) !== -1 ) {
                    hasAttribute = true;
                    return false;  // to halt the iteration
                }
            });
    
            return hasAttribute;
        }
    });
    

    $('img:attrNameStart(data-plugin)')
    

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