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 /> 

I try to find all dom nodes with attribute name starting with data-validate-

As far as I understand, wildcards here are associated with the "value" of the attribute.

The reason for this is - I want to find out which items should be checked at all, and then find out which check options (e.g. -email) come into play.

thanks

+4
source share
4 answers

You can create a custom pseudo-class, for example. map attribute names to 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; }; }); 

Using:

 $(":attr('^data-')") 
+5
source

Since jQuery relies heavily on XPath , and XPath does not support the choice of substitution attributes, this is impossible without the overhead of hoping to avoid it.

It is always possible to create your own selector to keep it 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; } }) 

This will allow you to use: dataValidate in your regular jQuery selectors:

 $(".element:dataValidate .etc") 

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

+3
source

You can iterate over attributes:

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

You can use the filter method and dataset object:

Allows access, both in read and write mode, to all attributes of user data (data- *) set in the element. This is a DOMString map, one entry for each user 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/

+2
source

Source: https://habr.com/ru/post/1443988/


All Articles