JQuery - select all elements with attribute name (not value) starting with ...?

Let's say that I'm looking for all the elements with the attribute 'data-language', the value of which begins with 'java' (it will match both "java" and "javascript"). I know how to do this:

$('[data-language^="java"]') 

But my question is: how do I get all the elements that have an attribute ( not the value of the attribute, but the name of the attribute itself ), starting with something? For instance:

  • all elements with an attribute name starting with "data-s", or
  • all elements that have data attributes in general (attributes starting with "data -").
+3
source share
2 answers

There is no shortcut, you can use the attributes collection:

  $(someselector).filter(function(){ var attrs = this.attributes; for (var i=0; i<attrs.length; i++) { if (attrs[i].name.indexOf("someStartOfName")==0) return true; } return false; }); 
+8
source

jQuery has a nice feature for this.

http://api.jquery.com/data/

 $("div").data() // returns all data attributes to this div 
0
source

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


All Articles