Amberlamps
Amberlamps

Reputation: 40448

How to access element via dataset attribute directly

Assuming I have following mark up:

<div id="Movie" data-genre="horror">The Hills Have Eyes</div>

I know that I can access that element´s dataset attributes using:

document.getElementById("Movie").dataset.genre

or

document.getElementById("Movie").getAttribute("data-genre")

But is there a way to get all elements with the same genre without using any other feature? I am thinking about something like that:

document.getElementsByDataSetKey(key)

Upvotes: 19

Views: 20853

Answers (1)

Musa
Musa

Reputation: 97672

You could try querySelectorAll

document.querySelectorAll('[data-genre~="horror"]');

will give you all elements with data genre that contains horror.

Upvotes: 38

Related Questions