最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Find HTML based on partial attribute - Stack Overflow

programmeradmin4浏览0评论

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 find partial attribute values as referenced in these links:

  • starts with [name^="value"]
  • contains prefix [name|="value"]
  • contains [name*="value"]
  • contains word [name~="value"]
  • ends with [name$="value"]
  • equals [name="value"]
  • not equal [name!="value"]
  • starts with [name^="value"]

but more something along the lines of

<div data-api-src="some value"></div>
<div data-api-myattr="foobar"></div>

and

$("[^data-api]").doSomething()

to find any element that has an attribute that starts with "data-api".

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 find partial attribute values as referenced in these links:

  • starts with [name^="value"]
  • contains prefix [name|="value"]
  • contains [name*="value"]
  • contains word [name~="value"]
  • ends with [name$="value"]
  • equals [name="value"]
  • not equal [name!="value"]
  • starts with [name^="value"]

but more something along the lines of

<div data-api-src="some value"></div>
<div data-api-myattr="foobar"></div>

and

$("[^data-api]").doSomething()

to find any element that has an attribute that starts with "data-api".

Share Improve this question edited Aug 30, 2012 at 14:30 Thomas Jones asked Aug 30, 2012 at 14:19 Thomas JonesThomas Jones 4,96230 silver badges35 bronze badges 4
  • 2 This question may be helpful: jquery data selector – jrummell Commented Aug 30, 2012 at 14:23
  • 1 Will it always be a "data-" attribute? – Ian Commented Aug 30, 2012 at 14:24
  • @ianpgall more than likely, yes. They will be similar up to a point (like data-api), then the rest of the attribute name might have meaning. – Thomas Jones Commented Aug 30, 2012 at 14:26
  • @jrummell that still seems like I need to know the entirety of the datakey. In this case, I might have a family of data-api-* keys, and want to find anything that matches them – Thomas Jones Commented Aug 30, 2012 at 14:30
Add a comment  | 

2 Answers 2

Reset to default 10

This uses .filter() to limit the candidates to those that has data-api-* attributes. Probably not the most efficient approach, but usable if you can first narrow down the search with a relevant selector.

$("div").filter(function() {
    var attrs = this.attributes;
    for (var i = 0; i < attrs.length; i++) {
        if (attrs[i].nodeName.indexOf('data-api-') === 0) return true;       
    };
    return false;
}).css('color', 'red');

Demo: http://jsfiddle.net/r3yPZ/2/


This can also be written as a selector. Here's my novice attempt:

$.expr[':'].hasAttrWithPrefix = function(obj, idx, meta, stack) {
    for (var i = 0; i < obj.attributes.length; i++) {
        if (obj.attributes[i].nodeName.indexOf(meta[3]) === 0) return true;
    };
    return false;
};

Usage:

$('div:hasAttrWithPrefix(data-api-)').css('color', 'red');

Demo: http://jsfiddle.net/SuSpe/3/

This selector should work for pre-1.8 versions of jQuery. For 1.8 and beyond, some changes may be required. Here's an attempt at a 1.8-compliant version:

$.expr[':'].hasAttrWithPrefix = $.expr.createPseudo(function(prefix) {
    return function(obj) {
        for (var i = 0; i < obj.attributes.length; i++) {
            if (obj.attributes[i].nodeName.indexOf(prefix) === 0) return true;
        };
        return false;
    };
});

Demo: http://jsfiddle.net/SuSpe/2/


For a more generic solution, here's a selector that takes a regex pattern and selects elements with attributes that match that pattern:

$.expr[':'].hasAttr = $.expr.createPseudo(function(regex) {
    var re = new RegExp(regex);
    return function(obj) {
        var attrs = obj.attributes
        for (var i = 0; i < attrs.length; i++) {
            if (re.test(attrs[i].nodeName)) return true;
        };
        return false;
    };
});

For your example, something like this should work:

$('div:hasAttr(^data-api-.+$)').css('color', 'red');

Demo: http://jsfiddle.net/Jg5qH/1/

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

发布评论

评论列表(0)

  1. 暂无评论