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
Release: 2024-10-27 12:16:30
Original
438 people have browsed it

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>
Copy after login

The following code snippets will not work as expected:

<code class="css">#test#1 {
  color: red;
}</code>
Copy after login
<code class="jQuery">$('#test#2').css('color', 'blue');</code>
Copy after login

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>
Copy after login
<code class="jQuery">$('#test\#2').css('color', 'blue');</code>
Copy after login

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>
Copy after login
<code class="css">#test\.1 {
  color: red;
}</code>
Copy after login
<code class="jQuery">$('#test\.1').css('color', 'blue');</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template