admin管理员组

文章数量:1332377

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

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-").
Share edited Dec 18, 2014 at 20:12 jbyrd asked Sep 23, 2013 at 15:36 jbyrdjbyrd 5,6159 gold badges56 silver badges93 bronze badges 7
  • 1 I think we all mis-read this, you want to find all elements that have an attribute beginning with data-, so, you want all elements containing a custom data attribute, yes? – tymeJV Commented Sep 23, 2013 at 15:38
  • Yes, exactly! Sorry, I can see how it could be misread. – jbyrd Commented Sep 23, 2013 at 15:41
  • 2 I figured those bolded words meant something important :) – tymeJV Commented Sep 23, 2013 at 15:41
  • haha - ok, I've updated the question - hopefully it's a little clearer now. – jbyrd Commented Sep 23, 2013 at 15:43
  • "I know how to get all elements that have an attribute value beginning with something: $('[data-size^="value"]')" That won't do that. – j08691 Commented Sep 23, 2013 at 15:50
 |  Show 2 more ments

2 Answers 2

Reset to default 9

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

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

本文标签: javascriptjQueryselect all elements with attribute name (not value) beginning withStack Overflow