Home >Web Front-end >CSS Tutorial >How to Use \'#\' in CSS and jQuery Selectors with Hashtags?

How to Use \'#\' in CSS and jQuery Selectors with Hashtags?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 12:16:30432browse

How to Use '#' in CSS and jQuery Selectors with Hashtags?

Using '#' in CSS and jQuery Selectors with Hashtags

The Issue

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>

The Solution

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>

Recommendation

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.

Escaping '.' in IDs

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn