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".
Not sure what it is you're looking for, but just spent a few minutes writing this:
To be used like :
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
This uses
.filter()
to limit the candidates to those that hasdata-api-*
attributes. Probably not the most efficient approach, but usable if you can first narrow down the search with a relevant selector.Demo: http://jsfiddle.net/r3yPZ/2/
This can also be written as a selector. Here's my novice attempt:
Usage:
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:
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:
For your example, something like this should work:
Demo: http://jsfiddle.net/Jg5qH/1/