Find DOM element by ID when ID contains square brackets?

You need to escape the square brackets so that they are not counted as attribute selectors. Try this:

alert($("#something\\["+id+"\\]").parent().parent().attr("id"));

See Special Characters In Selectors, specifically the second paragraph:

To use any of the meta-characters (such as !"#$%&'()*+,./:;<=>?@[\]^``{|}~) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.

Leave a Comment