I\'m going to use various data attributes names start with for example \"data-mo-\"
.
Assume I have these elements:
A concise approach using ES6 is to select all elements in the document, then .filter
by whether .some
of the attribute names start with the string you're looking for:
const moElements = [...document.querySelectorAll('*')]
.filter(elm => [...elm.attributes].some(
({ name }) => name.startsWith('data-mo-')
));
console.log(moElements);
Title 1
Title 2
Title 3
Title 4
somethingElse
Or, if you want to avoid constructing the intermediate arrays with spread, you can .call
the array methods on the element / attribute collections instead:
const moElements = Array.prototype.filter.call(
document.querySelectorAll('*'),
elm => Array.prototype.some.call(
elm.attributes,
({ name }) => name.startsWith('data-mo-')
)
);
console.log(moElements);
Title 1
Title 2
Title 3
Title 4
somethingElse