Home >Web Front-end >CSS Tutorial >How to Use \'#\' in CSS and jQuery Selectors with Hashtags?
Consider the following HTML:
<code class="html"><div id='test#1'>test1</div> <div id='test#2'>test2</div></code>
The following code snippets will not work as expected:
<code class="css">#test#1 { color: red; }</code>
<code class="jQuery">$('#test#2').css('color', 'blue');</code>
To use metacharacters like '#' as a literal part of a name, they must be escaped with a backslash:
<code class="css">#test\#1 { color: red; }</code>
<code class="jQuery">$('#test\#2').css('color', 'blue');</code>
It's best to avoid using '#' in your IDs for consistency and to follow web standards. IDs must start with a letter and can only contain letters, numbers, hyphens, underscores, colons, and periods.
If an ID contains '.', you should also escape it:
<code class="html"><div id='test.1'></div></code>
<code class="css">#test\.1 { color: red; }</code>
<code class="jQuery">$('#test\.1').css('color', 'blue');</code>
The above is the detailed content of How to Use \'#\' in CSS and jQuery Selectors with Hashtags?. For more information, please follow other related articles on the PHP Chinese website!