24

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?

Gicminos
  • 912
  • 3
  • 10
  • 32

6 Answers6

52

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.

Jeremy
  • 1
  • 85
  • 340
  • 366
8

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>
blurfus
  • 13,485
  • 8
  • 55
  • 61
  • Only if the value of `name` is a [CSS identifier](https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier). – Oriol May 06 '16 at 21:35
  • fair comment, thx - directing readers to the better answer that handles the case when it's not a CSS Identifier – blurfus May 06 '16 at 21:41
5

you could also do this

let name = 'Paul'
document.querySelector('.'+ name)

then you do not need a data-name

coding-i-like
  • 61
  • 1
  • 1
0

This works in Typescript:

document.querySelector(\`[data-name=${name}]`)
jxramos
  • 7,356
  • 6
  • 57
  • 105
Kevin Leto
  • 17
  • 4
0
<div class="test" data-name="Paul"></div>

Try in this way it may be work :-

var username = "Paul";

document.querySelector(`[data-name="${username}"]`);
Althaf Ahd
  • 1
  • 1
  • 1
-1

I'm super late to this party but check out the code snippet - it shows you how to get the current value of data-name and also how to change the value

    let test = document.querySelector('.test');
    // get the current value of data-name
    let name = test.dataset.name;
    console.log('current value of data-name: ' + name)

    // change the value of data-name
    let newName = 'Jimmy'
    console.log(test.dataset.name = newName);
<div class="test" data-name="Paul"></div>