-2

Given that I have a document similar to this:

<div>
    <div data-myAttr = "foo"></div>
    <div data-myAttr = "bar"></div>
</div>
<div>
    <div data-myAttr = "foo"></div>
    <div data-myAttr = "bar"></div>
</div>

How can I get all elements that contain data-myAttr with foo's and bar's grouped?

Edit: this is more of a theoretical question. I have no tried code that has failed but am exploring a more elegant option for code that already exists.

BTW, thank you for the -1!?

Edit: can someone mark this as duplicate? Found applicable answer here: Group and count HTML elements by data attribute in jQuery

Community
  • 1
  • 1
Chris Stahl
  • 1,712
  • 3
  • 14
  • 16

2 Answers2

2

Ok this is my first ever answer on here so don't judge to harshly... In my case I had duplicates in my array as well. And I am only just starting to fully understand how this all works but here goes:

elements = $('div[data-myAttr]').map(function () {
    return $(this).attr('data-myAttr');
});

Then run a basic js loop by name to grab all elements with the correct attr.

TJ Sherrill
  • 2,465
  • 7
  • 50
  • 88
0

you can use attribute selector and combine two attribute selectors with comma;

Live Demo

$('[data-myAttr=foo], [data-myAttr=bar]')

You can iterate through the elements using each()

$('[data-myAttr=foo], [data-myAttr=bar]').each(function(){
  alert($(this).text());  
});
Adil
  • 146,340
  • 25
  • 209
  • 204