Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - select all elements with attribute name (not value) beginning with...?

Say I'm looking for all elements with an attribute 'data-language', whose value begins with 'java' (would match both 'java' and 'javascript'). I know how to do this:

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

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

  1. all elements that have an attribute name beginning with "data-s", or
  2. all elements that have data attributes at all (attributes beginning with "data-").
like image 214
jbyrd Avatar asked Jan 13 '23 07:01

jbyrd


1 Answers

There is no shortcut, you may 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;
 });
like image 164
Denys Séguret Avatar answered Feb 08 '23 06:02

Denys Séguret