Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript: querySelector containing @ symbol is invalid

I have an element with a className containing an @ symbol.
Such as <div class="modify@s">

I can easily style this via a css selctor such as .modify\@s

But I can’t use this selector to target the element via querySelector in javascript.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

document.querySelector('.modify@s') 
document.querySelector('.modify\@s')

‘… is not a valid selector"

How can I select this element by its specify className?

Below a demo to play around with presenting the issue.

// this could be wrapped in a media query, so the @s reflects the mediaquery
.modify\@s {
  background: red;
}
<div class="baseClass">BaseClass nothing special here</div>
<div class="baseClass modify@s">Modify with background</div>

<button onclick="document.querySelector('.modify@s').style.border = '3px solid blue';">select modify element and add border (causes error in console)</button>
 <button onclick="document.querySelector('.modify\@s').style.border = '3px solid blue';">select modify element (with escaped @) and add border  (causes error in console)</button>

>Solution :

The @ is valid in a class name but needs to be escaped in CSS (I presume that’s to avoid clashes with at-rules). But it turns out the escape symbol used by CSS (\) is the same as the escape symbol used by JavaScript. That means you need to escape it twice.

// this could be wrapped in a media query, so the @s reflects the mediaquery
.modify\@s {
  background: red;
}
<div class="baseClass">BaseClass nothing special here</div>
<div class="baseClass modify@s">Modify with background</div>

<button onclick="document.querySelector('.modify\\@s').style.border = '3px solid blue';">select modify element and add border (no longer causes error in console)</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading