Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
JavaScript escape quotes when selecting element by attribute value

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!