jQuery: How to access an element with a plus sign (+) in the id

jquery, variables

Solution

It doesn't work, because the `+` sign is a so called meta-characters in jQuery's selector as explained in the documentation. You should escape it using 2 backslashes:

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.

So, in your case, you would do (see jsFiddle):

var test = $("#expand-icon" + currentID.replace(/\+/g, '\\+')).attr("src");
var testID = $("#row-icon" + currentID.replace(/\+/g, '\\+')).attr("id");

Problem

I have a jQuery loop that appends multiple rows to a table. The number of rows can change at run-time, so the row ID is generated dynamically. ``` $("#tableBody") .append($("<tr>") .attr('id','row-icon' + currentID)... ``` At a later point, I then need to access these added rows. However, when the value of `currentID` has a '+' symbol in it - I get an "undefined" error when I try to access the row element. For example, the line below works when `currentID` is "1" - but it fails when the ID is "vm+1". ``` var testID = $("#row-icon" + currentID).attr("id"); ``` Am I missing an easy solution to "escape" the extra '+' symbol? Working example here. EDIT: I should note that the id's are being sent by a 3rd-party - so I have no control over removing the '+' symbol.

Original source

Related problems