Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda