1

So I found a solution to what I need here. The latest updated solution in that thread suggested using this line to retrieve elements by its data attribute:

document.querySelectorAll('[attribute=value]')

My question: that line hardcodes the value to the syntax. If I need to pass value from a variable, something like :

document.querySelectorAll('[attribute=]' = myVar)

For example, I want to select all elements with data-genre attribute set to horror. What is the correct syntax? The line below does not work.

let myVar = "horror"
document.querySelectorAll('[data-genre]' = myVar)

Thanks.

Tristan Tran
  • 1,351
  • 1
  • 10
  • 36
  • 1
    Traditionally, string concatenation is all you need. These days, this is best solved using [template string literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), like this: `document.querySelectorAll(\`[attribute=]=${myVar}\`)`. – costaparas Dec 30 '20 at 11:06

0 Answers0