How to find all elements that have attributes that match pattern data-foo-bar-*
, e.g.
<div data-foo-bar-id="" />
Using document.querySelectorAll
with foo-bar-*
pattern gives error:
Uncaught SyntaxError: Failed to execute 'querySelectorAll' on 'Document': '[data-foo-bar-*]' is not a valid selector.
Maybe iterating through all DOM elements and looking for this specific attribute might not be the best approach, but here's my try:
function querySelectorPattern(regex, element) {
var elements = document.getElementsByTagName(element),
found,
regexp = new RegExp(regex);
for (var i = 0; i < elements.length; i++) {
var attributes = elements[i].attributes;
for (var k = 0; k < attributes.length; k++) {
if(regexp.test(attributes[k].nodeName)) {
console.log(elements[i]);
}
}
}
}
And a quick demo: https://jsfiddle.net/1rsngvy8/
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