0
<div data-start-one="one"></div>
<div data-start-one="one"></div>
<div data-start-two="two"></div>
<div data-start-three="three"></div>

How can I retrieve all elements that have a jQuery attribute that starts with data-start?

For example: $("div[data-start-*]")

jefiwo
  • 111
  • 1
  • 1
  • 6

1 Answers1

1

There's no good way to do this. You'll have to iterate over all elements that might match what you want, then filter them out.

const starts = $('div').filter(function() {
  return [...this.attributes].some(
    attrib => attrib.name.startsWith('data-start')
  );
});
console.log(starts.length);
console.log(starts[3]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-start-1="one"></div>
<div data-start-1="one"></div>
<div data-start-2="two"></div>
<div data-start-3="three"></div>
<div class="somethingElse"></div>

A much better approach would be to be able to select these elements using something else in common, like a class or another data attribute or a descendant of a container.

const starts = $('.container div');
console.log(starts.length);
console.log(starts[3]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div data-start-1="one"></div>
  <div data-start-1="one"></div>
  <div data-start-2="two"></div>
  <div data-start-3="three"></div>
</div>
<div class="somethingElse"></div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320