5

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");
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Pradeepal Sudeshana
  • 908
  • 2
  • 14
  • 30

3 Answers3

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.com/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>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 1
    There's also a limitation in this example that prevents you from distinguishing between `data-my-foo` and `data-myfoo`, should you want to exclude the latter. But if you can guarantee that the latter will never occur, this example will serve you just fine. – BoltClock Sep 01 '18 at 07:23
2

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");
    });
});
Pirai Sudie
  • 162
  • 3
  • 17
2

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.com/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>
Jeto
  • 14,596
  • 2
  • 32
  • 46