4

I want to find and select all element which have data attribute start with "data-qu" under wrapper div. How can I do this with 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 select those, like this $('.wrapper').find('^data-qu') or similar?

midstack
  • 2,105
  • 7
  • 44
  • 73

3 Answers3

5
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;
});
Piotr Czarnecki
  • 1,688
  • 3
  • 14
  • 22
4

ref: jQuery attribute name contains

you can do like this.

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

  return false;
});​
Community
  • 1
  • 1
Raghavendra
  • 3,530
  • 1
  • 17
  • 18
2

Try utilizing .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>
guest271314
  • 1
  • 15
  • 104
  • 177
  • why so you can directly use the html of element itself to match – Raghavendra Aug 31 '15 at 14:16
  • @Raghavendra _"why so you can directly use the html of element itself then "_ Not certain interpret comment correctly ? – guest271314 Aug 31 '15 at 14:18
  • @guest271314 $('.wrapper *') does universal selector cause low performance?If we think like CSS selectors – midstack Aug 31 '15 at 14:19
  • i mean you can match '
    '.match(/qu.*?>/). why objects keys all things
    – Raghavendra Aug 31 '15 at 14:21
  • @Raghavendra jQuery `.data()` stores `data-*` attribute as `Object` having key / value pairs ; where `key` is name , or `*` of `data-*` ; e.g.,`qu-lw` – guest271314 Aug 31 '15 at 14:22
  • anyway it helps the answer bye – Raghavendra Aug 31 '15 at 14:23
  • @midstack _"$('.wrapper *') does universal selector cause low performance?"_ See at Question _"want to find and select **all element** which data attribute start with "data-qu" under wrapper div"_ Is requirement to select _all_ elements which have `data-*` beginning with `"qu"` , or only `div` elements ? – guest271314 Aug 31 '15 at 14:29