Given HTML:
<div class="element" data-name="cat">
<div class="element" data-name="bird">
<div class="element" data-name="dog">
I want to find only the elements that match a data attribute that im keeping in an array like this
let Array1 = ["dog","cat","lizard"]
I thought I could do it with querySelectorAll and data attribute filter but its not working at all. Returns an empty nodelist.
let Elements = document.body.querySelectorAll('.element[data-name="${Array1}"]')
Im working on a firefox extension looking at a webpage, so I can’t touch the HTML and would prefer to stay in pure javascript. Im very new at programming and this is a personal project.
2
Answers
Unfortunately, there’s no shortcut. I would recommend to loop through your array of possible values. Since
querySelectorAll
returns aNodeList
, you need to use spread syntax (...
) to expand it into your array of captured elements.Explanation
There is no direct way to do that, because the querySelector is designed to only select elements based on a single css/attribute selector. However, we can achieve that by repeating the query for multiple times.
Code