Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda