List all "date" attributes that contain a certain code

0

I need to list all data faults that contain certain code in their name ( not in value ).

HTML tag example 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 data related to their respective information, in this case, the abc (which I put for testing only).

I'm using jQuery and using attr() to insert, however, I can switch to data() if needed.

Could anyone help me?

    
asked by anonymous 16.11.2015 / 23:16

2 answers

0

With this small snipet you can list all the attributes with data at the beginning of the name in 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 loop all the attributes of a certain element, and filters listing only those that start with data- , from there you can do anything with them.

    
17.11.2015 / 03:17
1

I've developed a method for you to do this in pure javascript. About performance, I did no testing.

Method : Pure JavaScript, using the document.getElementsByTagName('*'); function to get all elements of the page, passing loops , the first checks elements and the second attributes. By passing a regular expression as a parameter, the function makes a match() checking if the attribute is valid and in the case below returning all elements whose attribute has data and 2013 (2013 is the differentiated 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 working method on jsfiddle

    
17.11.2015 / 12:27