3

I have a list of div, each has an id. The id also performs as a link: "http://en.wikipedia.org/wiki/" + id is the link to this item on wikipedia, "/image/" + id + ".jpg" is the local image for this item.

But I have some id with special characters. There are two types (that I found have bug): first, A_(B), containing parentheses, second A%C3%A9B (AéB), containing special letter. I know () can be replaced by %28%29, so it is basically only one type. And I have tested, this kind of name works for image and wiki link.

The problem is, when I use jQuery, $('#' + id) cannot find those objects with special letters. Anyone has any idea how to deal with it?

Rob W
  • 341,306
  • 83
  • 791
  • 678
DrXCheng
  • 3,992
  • 11
  • 49
  • 72

4 Answers4

3

If you look at the second paragraph of the selectors page, it shows you that these characters !"#$%&'()*+,./:;<=>?@[\]^``{|}~ need to be escaped when used.

But if you are including other characters it might be best to use their escape code to include them ( google closure compiler will automatically do this for you ). So this letter é can be replaced with \u00e9

Mottie
  • 84,355
  • 30
  • 126
  • 241
1

have you tried:

var id = encodeURIComponent(id);
$('#' + id);

to see if it resolves it?

Robert Van Sant
  • 1,497
  • 10
  • 12
0

See this SO question for more info.

Personally, I believe IDs should conform to human-readable, easily-understandable IDs. Consider attaching URLs using a different mechanism, like jQuery's $.data, or another property that doesn't have validity restrictions.

Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

A good rule of thumb is to first conform to relevant specifications. According to HTML 4.01:

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 characters like (, ) and % are not allowed in element ids or names.

Non-conforming characters in ids are likely to cause issues other than with jQuery. Using encodeURIComponent (e.g. to replace ( with %28) doesn't help because the % character isn't allowed either. But you can get away with character entities for letters outside the typical a-z,A-Z range, or you could just use plain old document.getElementById and if you really need to use jQuery:

$(document.getElementById(id))

may be sufficient (but not reliable).

RobG
  • 142,382
  • 31
  • 172
  • 209