Use variables in document.querySelector
You need to concatenate the strings, like:
document.querySelector("[data-name=" + name + "]");
For example:
(See @Jeremy Bank's answer for a much better answer, tho)
var name = "Paul";
var element = document.querySelector("[data-name=" + name + "]");
alert(element.nodeName);
<div class="test" data-name="Paul">
test.
</div>
You can do that, but you need to use the CSS.escape()
function to ensure the value is properly encoded for use in a CSS expression.
var name = "hello, world!";
document.querySelector("[data-name=" + CSS.escape(name) + "]");
<div data-name="hello, world!">…</div>
ES2015:
const name = "hello, world!";
document.querySelector(`[data-name=${CSS.escape(name)}]`);
If you don't use CSS.escape(...)
then certain values of name
could cause your code to throw an error instead.
var name = "hello, world!";
document.querySelector("[data-name=" + name + "]");
Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '[data-name=hello, world!]' is not a valid selector
If you're targeting a browser which doesn't natively support CSS.escape()
you can use this polyfill by Mathias Bynens.