Find HTML based on partial attribute

后端 未结 2 1778
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 03:12

Is there a way with javascript (particularly jQuery) to find an element based on a partial attribute name?

I am not looking for any of the selectors that fi

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 03:37

    Not sure what it is you're looking for, but just spent a few minutes writing this:

    $.fn.filterData = function(set) {
        var elems=$([]);
        this.each(function(i,e) {
            $.each( $(e).data(), function(j,f) {
                if (j.substring(0, set.length) == set) {
                    elems = elems.add($(e));
                }
            });
        });
        return elems;
    }
    

    To be used like :

    $('div').filterData('api').css('color', 'red');
    

    And will match any elements with a data attribute like data-api-*, and you can extend and modify it to include more options etc. but of right now it only searches for data attributes, and only matches 'starts with', but at least it's simple to use ?

    FIDDLE

提交回复
热议问题