How to take id as selector when used hash?

Suppose of the following html:

<div id='test#1'>test1</div>
<div id='test#2'>test2</div>

Now, the following wouldn't work, why?

css....

#test#1{color: red;}

jQuery....

$('#test#2').css('color','blue');

Solution 1:

To use any of the meta-characters such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ as a literal part of a name, it must be escaped with with backslashes:

css way:

#test\#1{
    color: red;
}

jquery way:

$('#test\\#2').css('color','blue');

demo


Recommendation:

You should not use # in your id see more for detail

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").


So, you may be also wondering id="test.1" can be used and for this too you should escape the character as described above.

Solution 2:

You can escape the # with backslash \:

#test\#1{
    color: red;
}

with jQuery, you can do the same way but you need to escape the \ with another backslash:

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\

$('#test\\#2').css('color','blue');

Fiddle Demo

However, # is not a valid unique identifier according to HTML 4 specification:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

and HTML 5 specification as well:

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

So you should remove second # in your id.

Solution 3:

you have to use \ when using special characters

var test1 = $('#test\\#1');

http://bugs.jquery.com/ticket/4944