-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

2
  • 3
    Please post the code you have tried that did not work. Commented Apr 8, 2013 at 15:39
  • For exploring more elegant options to already working code, consider codereview.stackoverflow.com , and you'll still want to post your code. Commented Apr 8, 2013 at 15:48

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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());  
});

3 Comments

Thanks for the answer but, is it possible to do this without having to define the data-myAttr value?
Sorry, I meant without having to define it as part of the selector. Thank you, though!
Can you explain "without having to define it as part of the selector"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.