I have a variable that can contain both single quotes and double.
Using this variable, I want to select an element whose attribute value is equal to that variable. I do this with a CSS attribute selector like so:
const cat = "Children's/Kids";
const div = document.querySelector(`[category='${cat}']`);
<div category="Children's/Kids"></div>
Currently, if the variable contains single quotes or double quotes, it doesn't work, as cat
is wrapped in single quotes in the selector, and if cat
contains a single quote, the final selector result will have an unclosed quote.
For example, the selector in the above example will be [category='Children's/Kids']
, which will produce a DOMException
since it is an invalid selector.
If it doesn't contain quotes, it works.
Solutions? Thanks
CodePudding user response:
You can let JSON.stringify
handle the quote escaping for you:
const cat = "Children's/Kids";
const div = document.querySelector(`[category=${JSON.stringify(cat)}]`);
console.log('Selector:', `[category=${JSON.stringify(cat)}]`)
console.log('Element:', div)
<div category="Children's/Kids"></div>