Select items starting with "data-"

How can I select, with javascript or jQuery plan, every element that has an attribute starting with "data -"?

I tried

$("[data-*"]) 

but that will not work.

+6
source share
1 answer

Here is a function other than jQuery 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 } 

What can be used like this:

 var results = getAllDataElements(); results.forEach(function (i) { i.style.color = "#FF0000"; }); 

Here is a working example

+5
source

Source: https://habr.com/ru/post/953140/


All Articles