ES6 solution :
const attrStartsWith = (prefix) =>
Array.from(document.querySelectorAll('*'))
.filter(
(e) => Array.from(e.attributes).filter(
({name, value}) => name.startsWith(prefix)).length
)
Then :
attrStartsWith('ng-') // return an array of HTML elements which have attributes name starts with "ng-"
versions of 2017-12-02
const queryByAttrNameStartsWith = (contextualSelector = '*') => {
const elements = Array.from(document.querySelectorAll(contextualSelector));
return (prefix) =>
elements.filter(e =>
Array.from(e.attributes).find(({ name, value }) =>
name.startsWith(prefix)
)
);
};
//then
queryByAttrNameStartsWith('*')('data-'); // all elements that have attribute name that starts with 'data-'
queryByAttrNameStartsWith('div')('ng-'); // ony DIV elements that have attribute name that starts with 'ng-'
//.. so on
or :
NodeList.prototype.filterByAttrNameStartsWith = function(prefix) {
return Array.from(this).filter(e =>
Array.from(e.attributes).find(({ name, value }) => name.startsWith(prefix))
);
};
//then
document.querySelectorAll('*')
.filterByAttrNameStartsWith('data-'); // all elements that have attribute name that starts with 'data-'
document.querySelectorAll('div')
.filterByAttrNameStartsWith('ng-'); // ony DIV elements that have attribute name that starts with 'ng-'
//.. so on