I'm trying to implement this W3 description of character escapes in CSS class selectors.
I'm running into problems with the abc\20 def
syntax that puts a space after the escape sequence to ensure def
is not misread as part of the character code.
Specifically, trying to put abc\XY def
into an HTML class attribute or into a command like jQuery().addClass('abc\\20 def')
(the \\
here is part of the JS string literal syntax; the string value itself has one slash) will both give the element two classes, abc\20
and def
.
Is this syntax just badly implemented, and I should stick with the six-digit leading zero form? Or does that document only refer to the escape format in CSS code, and the HTML attribute / jQuery argument require some different form of escaping the space character?
Edit: Thank you very much for explaining, everyone!
I now understand that this syntax only applies to CSS code - not the class names themselves as set in HTML attributes or Javascript.
This also means that characters designated as whitespace can't occur in CSS class values, and no kind of escape mechanism allows them to be added. (Specifically, if I understand correctly, the CSS selector .abc\20 def
is valid and selects elements with the class abc def
, but is meaningless because no element can have this class.)
For my concrete use case, which involves mapping arbitrary values (which can have white space) to valid class names, I need to define my own escape scheme. Replacing whitespace with -
or _
(thanks Praveen) is one possibility; if the mapping needs to be one-to-one, replacing them with six-digit Unicode hex values (eg. "abc def" -> "abc\000020def"
is a more robust one.
The important thing to keep in mind is that this replacement affects the class name itself - to refer to the class abc\000020def
in CSS, the backslash must be escaped again, to form the selector .abc\\000020def
.