简体   繁体   中英

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

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

jQuery has a nice function for this.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM