0

Is there a basic way via jquery to find all elements that have a data-attribute with a specific value and return those elements as an array?

i.e. <span data-productID="7">My product</span>

1
  • note, data attributes are normalized to be all lowercase. If you want it to be represented by productId in jQuery's .data method, use data-product-id="7" Commented Mar 18, 2013 at 21:04

1 Answer 1

2

The syntax for selecting elements with a specific attribute value is:

[attr_name = attr_value]

In your specific case, this would be:

$('span[data-product="7"]');

This returns a jQuery collection (not an Array), but it can be accessed much like an array using numerical indices. If you really need an array (perhaps in order to use Array prototype methods), you can use:

$('span[data-product="7"]').makeArray();
Sign up to request clarification or add additional context in comments.

2 Comments

What is the collection returned a collection of? i.e. elements? I am trying to figure out how to manipulate the classes of each element in the collection.
@JohnS The collection wraps elements that match the expression in the selector string. To apply a class to the elements in a collection, use $(selector).addClass('myclass'). To remove a class, use removeClass, in much the same way.

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.