I need to select all elements, which have an attribute starting with a given prefix - note I am talking about the attribute name, not value. For example:
<div data-abc-name="value">...</div>
<a href="..." data-abc-another="something">...</a>
<span data-nonabc="123">...</span>
In the above HTML, I need to get all elements that have an attribute starting with data-abc-
- that is, the div
and the a
.
How can I do that?
You can do it like this by ES6:
$('*').filter(function() {
for (attr of this.attributes)
if (attr.name.startsWith("data-abc"))
return this;
});
Online demo (jsFiddle)
I don't think we have jQuery
selector with regex
. However you can make use of this
Until you find a proper selector, here is a small workaround, that selects elements with matching attribute
var nodes = [];
$("body > *").each(function(){ //iterating over all nodes
$(this.attributes).each(function(){
console.log(this.nodeName);
if(this.nodeName.indexOf("data-abc") > -1){
nodes.push(this);
}
});
});
console.log(nodes.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-abc-name="value">...</div>
<a href="..." data-abc-another="something">...</a>
<span data-nonabc="123">...</span>
Here is my solutions - Fiddle. You have to create your own jquery selector.
jQuery.extend(jQuery.expr[':'], {
attrStartsWith: function (el, _, b) {
for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++) {
if(atts[i].nodeName.toLowerCase().indexOf(b[3].toLowerCase()) === 0) {
return true;
}
}
return false;
}
});
//e.g:
$('a:attrStartsWith("data-abc")').html('hello');
$('div:attrStartsWith("data-abc")').html('hello');