简体   繁体   中英

How can I select elements on dom (with jQuery) that has some data attribute that ends with “created”?

I have all my elements, on a project, that are being transferred with data attributes so the javascript can know what to do.

But I have one problem, one part of the application must get all the created variables to compare time, and I have they saved like ( data-product-created , data-category-created , data-link-created , etc...). It would be a huge headache if I had to put them manually on the jQuery selector...

Do jQuery has some method to search custom data attributes existence?

Like: element[data-(.*)-created]

You could create a low level Javascript method to loop through elements and pull their created values:

var getCreateds = function($els) {
    var returnSet = [];
    $els.each(function(i, el){
        var elDict = {'el': el};
        $.each(el.attributes, function(i, attr){
            var m = attr.name.match(/data\-(.*?)\-created/);
            if (m) elDict[m[1]] = attr.value;
        });
        returnSet.push(elDict);
    });
    return returnSet;
};

See demo

Based on mVChr answer (THANK YOU), i've rewritten the code on a simple, better and clean code:

jQuery('div').filter(function(){
  for( var i in this.attributes ){
    if(typeof this.attributes[i] !== 'object') continue;
    if(this.attributes[i].name.match(/data\-(.*?)\-created/)) return true;
  }
  return false;
})

Changes:

+ Verifying attribute type... some attributes are browser internal functions or callbacks.
~ Using filter handler from jQuery, its better and cleaner way.
~ Using for instead of $.each, faster indeed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM