1

I'm trying to get the parent of an id with an extra # in front of it, but it isn't working. = Does the '#' cause this to malfunction? Or is there something wrong with the jQuery?

HTML:

<li><a href="blah" id="#id"></a></li>
<button id="clickme">click it</button>

jQuery:

$('#clickme').click(function() {
  ('##id').parent().addClass('active');
});

Any help would be appreciated.

alrightgame
  • 183
  • 1
  • 5
  • 17

5 Answers5

5

From the documentation:

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

So $('#\\#id') should work, though I really recommend to not use # as part of the ID, to avoid any possible problems. For example, I don't think there is away to escape the character in CSS rules (I could be wrong though) or using the ID as target (like <a href="##id"></a>) will probably not work either.

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
1

It's generally a bad idea with special characters in selectors, but you can always just escape them :

$('#clickme').click(function() {
    $('#\\#id').parent().addClass('active');
});

FIDDLE

adeneo
  • 293,187
  • 26
  • 361
  • 361
1

http://jsfiddle.net/mohammadAdil/exngF/

You need to escape that extra #

$('#\\#id')

more info here

http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/

In order to tell jQuery to treat these characters literally rather than as CSS notation, they must be "escaped" by placing two backslashes in front of them

Mohammad Adil
  • 43,337
  • 17
  • 86
  • 109
0

According to the W3C:

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 (".").

You really should not have an element with the ID #id. Yes, you can get around the parsing issue by escaping the extra hash as others have suggested, but a better solution would be to give the parent div a better ID, one that doesn't require special handling.

FishBasketGordo
  • 21,938
  • 4
  • 54
  • 88
  • 1
    True of HTML 4 but allowed in HTML5 http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – Turnip Apr 26 '13 at 19:47
  • 1
    I still say it isn't a very good idea. The version of HTML hasn't been specified, nor has the OP provided an extenuating circumstance for why the ID can't be changed. – FishBasketGordo Apr 26 '13 at 19:51
  • 1
    Subjective. Might make sense for some people and there coding practices. Though I won't do it myself – Turnip Apr 26 '13 at 19:53
-1

# is a special symbol reserved for ids. You shouldn't use it in the name of the id. Is there a specific reason why you would want to do this?

Cezary Wojcik
  • 21,065
  • 6
  • 34
  • 36