I have a list of div, each has an id. The id also performs as a link: "/" + 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?
I have a list of div, each has an id. The id also performs as a link: "http://en.wikipedia/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?
4 Answers
Reset to default 3If 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 piler will automatically do this for you ). So this letter é
can be replaced with \u00e9
have you tried:
var id = encodeURIComponent(id);
$('#' + id);
to see if it resolves it?
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.
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).