Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 668
madflow Avatar asked Dec 16 '22 17:12

madflow


2 Answers

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-')")
like image 153
pimvdb Avatar answered Dec 18 '22 09:12

pimvdb


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/

like image 35
Sean Johnson Avatar answered Dec 18 '22 09:12

Sean Johnson