You can do [foo^="bar"]
to match nodes which have the attribute foo
with value starting with bar
.
Is there a way to match nodes with an attribute name starting with a particular string? The use case of this is to match all nodes with a data-*
attribute.
Edit: the reason I'm trying this is to avoid iterating over all the nodes looking for these attributes (for performance reasons). I'd be using querySelectorAll
and its Sizzle polyfill for older browsers.
The CSS Attribute Selector is used to select an element with some specific attribute or attribute value. It is an excellent way to style the HTML elements by grouping them based on some specific attributes and the attribute selector will select those elements with similar attributes.
The [attribute~=value] selector is used to select elements with an attribute value containing a specified word.
The CSS id Selector The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.
One way is using .filter()
method:
$('element').filter(function() {
return $.grep(this.attributes, function(value) {
return value.nodeName.indexOf('data') === 0;
}).length;
});
http://jsfiddle.net/QACsw/
It may be a little overkill, but you could write a custom selector:
$.expr[':'].attr = function (elem, index, regex_str) {
var regex = new RegExp(regex_str[3]);
for (var i = 0; i < elem.attributes.length; i++) {
if (elem.attributes[i].name.match(regex)) {
return true;
}
}
return false;
};
Demo: http://jsfiddle.net/LBHwr/
So in your case, you'd do:
$('div:attr(^data)') // starts with
$('div:attr(foo$)') // ends with
It's somewhat similar to the regular attribute selector syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With