@Moob aproximation to jQuery attrBegins plugin, returns the attribute name (a string), when are matches... of a single element (ignoring multiple matches).
I addapted the code to return a JQuery Collection with the matching elements.
Here is the code:
(function($) {
$.fn.attrBegins = function(s) {
var matched = [];
this.each(function(index) {
var elem = this;
$.each(this.attributes, function( index, attr ) {
if(attr.name.indexOf(s)===0){
matched.push(elem);
}
});
});
return $( matched );
};
})(jQuery);
USAGE EXAMPLE...
HTML :
<div>
<div data-pet-dog></div>
<div data-pet-cat></div>
</div>
Javascript :
var foo = $("div").attrBegins("data-pet");
// results into... foo = [ <div data-pet-dog></div> , <div data-pet-cat></div> ]
NOTE: To prevent performance issues when selecting elements wich have an attribute name that starts with a custom string using attrBegins, is recomended to narrow as much as possible the original selector, to reduce the collection of elements to iterate.
attrBegins just filters the preselected elements collection, it does not explore the child elements of provided set of items.
data-
? Which value should you get? – Dubbingdata-
attribute. He wants to find the value of the attribute, not use it as a selector. – Maudmaude