1

In jQuery or JavaScript, I am wanting to get an element, or rather, select an element, by its data attribute, then apply a CSS class using addClass to the selected element.

Does anybody know how to do this? I've tried all the different .attr and .prop methods but they don't do what I want, as I don't know the ID or anything of the element beforehand, as it is set dynamically.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
JWDev
  • 856
  • 1
  • 10
  • 22

3 Answers3

3

You can use the jQuery selector:

$('[data-something="something"]')

Or starts With:

$('[data-something^="something"]')

Ends With:

$('[data-something$="something"]')

And then you can use:

$('[data-something="something"]').addClass(new_class_name);

The above will match all the elements having:

<tag data-something="something"></tag>

And give them a class new_class_name.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

Use the Attribute Equals Selector

$("p[data-yourdata='whatever']")
Andrew Brooke
  • 12,073
  • 8
  • 39
  • 55
0

If you would like to use a native JavaScript method and aren't worried about browser support for IE8 and below, you can use querySelector or querySelectorAll as explained in this answer: javascript: select all elements with "data-" attribute (without jQuery)

That said, if you're already tied to using jQuery's addClass and/or other selector methods it would probably be easier to stick to the selectors outlined above.

This answer gives a good breakdown of jQuery benefits/costs vs. native selectors: jQuery vs document.querySelectorAll

Community
  • 1
  • 1
Naomi
  • 61
  • 1