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 e.g. 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With