Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variables in document.querySelector

Tags:

javascript

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?

like image 551
Gicminos Avatar asked May 06 '16 21:05

Gicminos


People also ask

How do you set a value in document querySelector?

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].

How do I use querySelector with data attribute?

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.

Is it bad to use document querySelector in react?

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.

How do you document querySelector?

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.


2 Answers

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.

like image 93
Jeremy Avatar answered Sep 22 '22 16:09

Jeremy


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>
like image 27
blurfus Avatar answered Sep 18 '22 16:09

blurfus