jQuery - select all elements with attribute name (

2019-01-20 13:19发布

问题:

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-").

回答1:

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;
 });


回答2:

jQuery has a nice function for this.

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

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