Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements which start with "data-"

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.

like image 826
Fez Vrasta Avatar asked Sep 04 '13 09:09

Fez Vrasta


1 Answers

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

like image 119
musefan Avatar answered Oct 10 '22 01:10

musefan