简体   繁体   中英

Wildcards in HTML5 data attributes

Is it possible to find all DOM elements with jQuery with wildcards in the attribute name?

Consider the following HTML:

<input 
     id="val1" 
     type="text" 
     data-validate-required 
     data-validate-minlength="3" 
     data-validate-email />

What I am trying to achieve is to find all dom nodes with an attribute name starting with data-validate-

As far as I understand the wildcards described here are concerned with "value" of the attribute.

The reason for this is - I want to find out which elements should be validated at all - and afterwards find out which validation parameters (like -email) comes in play.

Thanks

You can create a custom pseudoclass to eg match attribute names against a regexp: http://jsfiddle.net/hN6vx/ .

jQuery.expr.pseudos.attr = $.expr.createPseudo(function(arg) {
    var regexp = new RegExp(arg);
    return function(elem) {
        for(var i = 0; i < elem.attributes.length; i++) {
            var attr = elem.attributes[i];
            if(regexp.test(attr.name)) {
                return true;
            }
        }
        return false;
    };
});

Usage:

$(":attr('^data-')")

Because JQuery relies heavily on XPath , and XPath does not support wildcard attribute selection - it is not possible without the overhead you're looking to avoid.

There's always the possibility of creating your own selector, just to keep things clean:

//adds the :dataValidate selector
$.extend($.expr[':'],{
    dataValidate: function(obj){
        var i,dataAttrs=$(obj).data()
        for (i in dataAttrs) {
                if (i.substr(0,8)=='validate') return true;
        }
        return false;
    }
})

Which will allow you to use :dataValidate in your normal jQuery selectors:

$(".element:dataValidate .etc")

Working JSFiddle: http://jsfiddle.net/rZXZ3/

You could loop over the atributes:

$('.element').each(function() {
  $.each(this.attributes, function(i, att){
     if(att.name.indexOf('data-validate')==0){
         console.log(att.name);
     }
  });
});

You can use filter method and dataset object:

Allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element. It is a map of DOMString, one entry for each custom data attribute.

$("input").filter(function(){
    var state = false;
    for (i in this.dataset) 
        if (i.indexOf('validate') > -1) state = true;

    return state             
})​

http://jsfiddle.net/Pxpfa/

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