How can I find and select all elements whose data attribute starts with a specific word using jquery?

I want to find and select all elements whose data attribute starts with "data-qu" under the wrapper div. How can I do this using jquery?

HTML

<div class="wrapper">
    <div data-qu-lw="1"></div>
    <div data-qu-md="2"></div>
    <div data-res-kl="1"></div>
    <div data-qu-lg="3"></div>
</div>

Is there a way to choose those that are similar to this $('.wrapper').find('^data-qu')or similar?

+4
source share
3 answers
var filteredElements = $('.wrapper > div').filter(function(){
  var attrs = this.attributes;
  for (var i=0; i<attrs.length; i++) {
      if (attrs[i].name.indexOf("data-qu")==0) return true;
  }         
  return false;
});
+5
source

ref: jQuery attribute name contains

You can do it.

$('.wrapper div').filter(function() {
  for (var property in $(this).data()) {
    if (property.indexOf('data-qu') == 0) {
      return true;
    }
  }

  return false;
});​
+4
source

.filter(), test(), Object.keys()

$(".wrapper *").filter(function() {
  return /^qu/.test(Object.keys($(this).data())[0])
}).css("color", "aqua")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
    <div data-qu-lw="1">1</div>
    <div data-qu-md="2">2</div>
    <div data-res-kl="1">1</div>
    <div data-qu-lg="3">3</div>
</div>
Hide result
+2

All Articles