You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何通过变量值使用document.querySelectorAll获取data属性元素?

How to select elements with a data attribute value from a variable using document.querySelectorAll

Great question! The problem with your initial attempt is that you’re not properly inserting the variable into the selector string. Here’s how to fix it correctly:

Using Template Literals (ES6+)

This is the cleanest and most readable approach for modern JavaScript. Wrap your entire selector in backticks () and use ${variable}` to inject the value directly into the string:

let myVar = "horror";
// Correct syntax
const matchingElements = document.querySelectorAll(`[data-genre="${myVar}"]`);

The template literal will automatically replace ${myVar} with the actual value of your variable, resulting in a valid selector like [data-genre="horror"].

Using String Concatenation (Older JS Environments)

If you need to support older browsers that don’t have ES6 support, you can build the selector string by concatenating parts together:

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

Quick Tip for Edge Cases

If your variable might contain special characters (like quotes, spaces, or CSS selector symbols), you’ll need to escape them to avoid breaking the selector. For example, if myVar could include a double quote, escape it first:

let myVar = "horror\"comedy";
const escapedValue = myVar.replace(/"/g, '\\"');
const matchingElements = document.querySelectorAll(`[data-genre="${escapedValue}"]`);

This ensures your selector stays valid even when dealing with unexpected characters in your variable.

内容的提问来源于stack exchange,提问作者Tristan Tran

火山引擎 最新活动