Question:
What's the best way to call an element that has square brackets in the name, using jQuery?.
HTML
<div name="name[1]"></div>
jQuery
$('div[name=name[1]]'); //errado?
$('div[name="name[1]"]'); //correto?
$('div[name="name\\[1\\]"]'); //correto?
$('div[name=name\\[1\\]]'); //correto?
Answer:
The first example $('div[name=name[1]]');
is incorrect, and gives the error unrecognized expression: div[name=name[1]]
.
The other options are correct, albeit for slightly different reasons.
Explanation:
-
$('div[name="name[1]"]')
is ok to use because jQuery treatsname[1]
as a string as it is inside quotes, not as a CSS/jQuery selector, and so it doesn't need to be shielded with the\\
escape. -
$('div[name="name\\[1\\]"]')
, works but doesn't need\\
. jQuery reads thename\\[1\\]
selector as a string as it is inside quotes, and in javascript the backslash causes the second slash to be ignored\
resulting in\[
, which in turn is the same as[
. So this example has backslashes unnecessarily. -
$('div[name=name\\[1\\]]')
is ok and the inner square brackets[]
must be shielded with backslashes in this way so as not to be confused with CSS/jQuery selectors.
From the jQuery documentation:
To use any of the following meta characters
!"#$%&'()*+,./:;<=>?@[]^`{|}~
as part of a name, they must be shielded with two backslashes, leading slashes: \\.
example here
More reading (in English):
- MDN – Escaping characters
- jQuery – Selectors
- W3.org – Characters