How can I select with plan javascript or jQuery every element which has an attribute that starts with "data-"?
I've tried
$("[data-*"])
but it doesn't work.
Here is a non-JQuery function that will do what you need:
function getAllDataElements() {
//get all DOM elements
var elements = document.getElementsByTagName("*");
//array to store matches
var matches = [];
//loop each element
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
//get all attributes for the element and loop them
var attributes = element.attributes;
for (var j = 0; j < attributes.length; j++) {
//get the name of the attribute
var attr = attributes.item(j).nodeName;
//check if attibute name starts with "data-"
if (attr.indexOf("data-") == 0) {
matches.push(element); //add it to matches
}
}
}
return matches; //return results
}
Which can be used like so:
var results = getAllDataElements();
results.forEach(function (i) {
i.style.color = "#FF0000";
});
Here is a working example
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