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.
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>
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>