Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  115] [ 6]  / answers: 1 / hits: 59927  / 8 Years ago, fri, may 6, 2016, 12:00:00

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?


More From » javascript

 Answers
1

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.


[#62273] Thursday, May 5, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackie

Total Points: 442
Total Questions: 107
Total Answers: 94

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
jackie questions
Sat, Sep 18, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
;