javascript - Wildcards in jQuery attribute's name selector? - Stack Overflow

How can I select all elements which contain data attributes starting with "data-my-" in the f

How can I select all elements which contain data attributes starting with "data-my-" in the following code? I'm not going to add wildcards to attribute value, It's attribute's name.

<p data-my-data="aa">foo</p>
<p data-my-info="bb">bar</p>

What I tried and failed:

$("[data-my-*]").addClass("myClass");

How can I select all elements which contain data attributes starting with "data-my-" in the following code? I'm not going to add wildcards to attribute value, It's attribute's name.

<p data-my-data="aa">foo</p>
<p data-my-info="bb">bar</p>

What I tried and failed:

$("[data-my-*]").addClass("myClass");
Share Improve this question edited Sep 1, 2018 at 7:28 BoltClock 725k165 gold badges1.4k silver badges1.4k bronze badges asked Sep 1, 2018 at 6:49 Pradeepal SudeshanaPradeepal Sudeshana 9602 gold badges15 silver badges32 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

You can't write a selector with a wildcard for attribute names. There isn't a syntax for that in the standard, and neither in jQuery.

There isn't a very efficient way to get just the elements you want without looping through every element in the DOM. It's best that you have some other way of narrowing down your selection to elements that are most likely to have these namespaced data attributes, and examine just these elements, to reduce overhead. For example, if we assume only p elements have these attributes (of course, you may need to change this to suit your page):

$("p").each(function() {
  const data = $(this).data();
  for (const i in data) {
    if (i.indexOf("my") === 0) {
      $(this).addClass("myClass");
      break;
    }
  }
});
.myClass {
  color: #f00;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p data-my-data="aa">foo</p>
<p data-my-info="bb">bar</p>
<p>baz</p>

there is no wildcarding for attribute names.so u can get result like below

$( "p" ).each(function( i ) {
    element=this;
    $.each(this.attributes, function() {
       if(this.name.indexOf('data-my-') != -1) $(element).addClass("myClass");
    });
});

Just a slightly shorter, but otherwise very similar version to @BoltClock's.

Note: using ES6 syntax.

$('p')
  .filter((_, el) => Object.keys($(el).data()).find(dataKey => dataKey.indexOf('my') === 0))
  .addClass('myClass');
.myClass { color: red; }
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p data-my-data="aa">foo</p>
<p data-my-info="bb">bar</p>
<p>baz</p>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744182499a4562047.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信