简体   繁体   中英

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)

You could try querySelectorAll

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM