How can you do the equivalent to
document.querySelectorAll(\'[data-foo]\')
where query
I played a bit around and ended up with this crude solution:
function getElementsByAttribute(attribute, context) {
var nodeList = (context || document).getElementsByTagName('*');
var nodeArray = [];
var iterator = 0;
var node = null;
while (node = nodeList[iterator++]) {
if (node.hasAttribute(attribute)) nodeArray.push(node);
}
return nodeArray;
}
The usage is quite simple, and works even in IE8:
getElementsByAttribute('data-foo');
// or with parentNode
getElementsByAttribute('data-foo', document);
http://fiddle.jshell.net/9xaxf6jr/
But I recommend to use querySelector
/ All
for this (and to support older browsers use a polyfill):
document.querySelectorAll('[data-foo]');