If I have:
<div class="test" data-name="Paul" >
and
var name = "Paul";
Can I use document.querySelector
to do something like this?
document.querySelector("[data-name=name]");
This doesn't work. What do I have to do?
value = 'random_value'; or if you want to use querySelectorAll, assuming there is only one element that matches the query: var elements = document. querySelectorAll("input[name=inputName]"); elements[0].
Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document. Here is the HTML for the examples in this article.
It's still possible to use querySelector in React, however, React encourages developers not to use it. Instead, we should aim to use refs if possible.
The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With