Reputation: 151
At the moment I'm writing a webchat, in which the user can open a new room with URI-GET params. The PHP part creates the html and sends it to the browser.
But if the user types in the URI something like /?Mychat%20%231
my PHP sends a chat named Mychat_#1
.
This still works correctly but when I try to refresh the chat (every second) I always get
SyntaxError: 'section.Mychat_#1' is not a valid selector
Every chat looks like this:
<section class="chat-container chat_name_#1"><!-- <- I try to get this node via the chat name -->
<header>
chat_name_#1
</header>
<div class="msg-container" style="">
<section><!-- here the messages will be inserted --></section>
</div>
<footer>
<div class="msg">
<input name="msg" autocomplete="off" type="text">
</div>
<div class="btn">
<button>senden</button>
</div>
</footer>
</section>
in my main.js file I tried to get the node with document.querySelector
for(DATA in CHAT){
let chat = document.querySelector('section.' + CHAT[DATA].title);
// ...
}
Normal the hashtag character is allowed in class names (if they don't start with it)
My Question is not a duplicate of Which characters are valid in CSS class names/selectors.
Before I asked it, I searched on Google and find it too. I read it but there was only explained, what CSS selectors are allowed. In my case it unfortunately didn't help.
Upvotes: 2
Views: 4643
Reputation: 723598
The hash is allowed in class names, but it represents an ID selector. This is the case even when your class name contains a hash. So your selector is being treated as a class selector followed by what appears to be an ID selector. The direct cause of the SYNTAX_ERR here is that ID selectors consist of a hash followed by an ident, and an ident cannot start with a digit (see section 4 of the CSS2 spec).
To use the hash in a class selector you need to escape it with a backslash, but if you have control over the PHP that generates these class names you're better off just doing away with the hash altogether as it only serves to cause more trouble than it's worth. Note that the hash also represents a fragment identifier in the URL, which is why it's encoded as %23
in your URL (see also Why is "#.id" a bad selector in CSS/jQuery yet it works in an HTML anchor?). So that's two reasons not to use a hash in a class name just because it's allowed in HTML5.
Upvotes: 3
Reputation: 164767
It seems that class selectors cannot have unescaped #
characters in them even though it is valid in the class
attribute. This is because an unescaped #
immediately signals an id
selector.
One option is to use an attribute selector. For example...
document.querySelector([
`section[class="${CHAT[DATA].title}"]`, // exact match, only one class
`section[class^="${CHAT[DATA].title} "]`, // starts-with
`section[class$=" ${CHAT[DATA].title}"]`, // ends-with
`section[class*=" ${CHAT[DATA].title} "]` // contains among other classes
].join(','))
Upvotes: 1