最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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>

发布评论

评论列表(0)

  1. 暂无评论