I'm going to use various data attributes names start with for example "data-mo-"
.
Assume I have these elements:
<span data-mo-top-fade-duration="600">Title 1</span>
<span data-mo-bottom-fade-duration="600">Title 2</span>
<span data-mo-right-fade-duration="600">Title 3</span>
<span data-mo-left-fade-duration="600">Title 4</span>
I know how to handle elements whose data attribute values start with some value, but how can it be done for the data attribute names?
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:Or, if you want to avoid constructing the intermediate arrays with spread, you can
.call
the array methods on the element / attribute collections instead:If all you wish to do is find whether a given node has an attribute beginning with a specific string, then one approach is the following:
JS Fiddle demo.
In the above all elements have an attribute starting with
data-mo
, to show it working more specifically, try:JS Fiddle demo.
This should match only the element which has an attribute starting with the string
data-mo-b
, styling only the second<span>
element.References:
Array.from()
.Array.prototype.filter()
.Array.prototype.forEach()
.document.querySelectorAll()
.Element.attributes
.Element.classList
API.Node.nodeName
.String.prototype.indexOf()
.If I get it right you want to check for data-mo so I have tried something to make this work;