List all "date" attributes containing a particular code

Asked

Viewed 366 times

0

I need to list all attributes data containing a code on their behalf (not in value).

Example of HTML tag with attributes:

<input type="hidden" id="products-end" data-flavor-id-15515-1="abc" data-flavor-pr-15515-1="abc" data-flavor-id-15515-2="abc" data-flavor-pr-15515-2="abc">

When searching for 15515-1 it would bring all the data related to their respective information, in the case, the abc (I just put it to the test).

I’m using jQuery and using attr() to insert, however, I can switch to the data() if necessary.

Could someone help me?

2 answers

1

I developed a method for you to do this, in pure javascript. About the performance, I did not make any test.

Method: Pure Javascript using the function document.getElementsByTagName('*'); to get all the elements of the page, going through two loops, the first checks elements and the second their attributes. Passing a regular expression as parameter, the function makes a match() checking if the attribute is valid and in the case below returning all the elements whose attribute has data and 2013 (2013 is the distinguishing code of the attribute name).

function getByAttr(regx) {
    Array.prototype.forEach.call(document.getElementsByTagName('*'), function(elem) {
        Array.prototype.forEach.call(elem.attributes, function(attr) {
            if(attr.name.indexOf('data') != -1 && attr.name.match(regx)) {
                console.log(elem);
            }
        });
    });
}
getByAttr(/2013/);

See the method working on jsfiddle

  • Thank you so much for your help. I didn’t get to test because it already worked on @Alanrezende, but thank you anyway.

0


With this little snipet you can list all attributes with data at the beginning of the name on the console, from there you can adapt it to your needs:

var item = $("#products-end");
$(item[0].attributes).each(function() { 
    if(this.name.indexOf('data-') == 0){
        console.log(this.name+':'+this.value);
    }
});

What it does is to loop all the attributes of a certain element, and filter by listing only those it starts with data-, from there you can do anything with them.

  • Hello, Alan. Thank you I used your method and it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.