How to use a name with square brackets in a jQuery selector?

What is the best way to call an element that has straight parentheses 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?
Author: Zignd, 2013-12-12

1 answers

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]"]') it is ok to use because jQuery treatsname[1] as a string, since it is inside quotes, and not as a CSS/jQuery selector, and thus does not need to be shielded with the escape \\.

  • $('div[name="name\\[1\\]"]'), works, but does not need from \\. JQuery reads the selector name\\[1\\] as a string because it is enclosed in quotes, and in javascript the backslash causes the second slash to be ignored\ resulting in \[, which in its view is the same as [. So this example has backslashes without need.

  • $('div[name=name\\[1\\]]') it is ok and the internal straight relatives [] have to be shielded with backslashes in this way so as not to be confused with selectors CSS / jQuery.

From the jQuery documentation:

To use any of the following meta-characters !"#$%&'()*+,./:;<=>?@[]^`{|}~ as part of a name, they must be shielded with two backslashes, left slashes: \\.

Example here


More reading):

 16
Author: Sergio, 2013-12-14 18:20:02