How to use a bracket name (brackets) in a jQuery selector?


What is the best way to call an element that has brackets in the name, using jQuery?


<div name="name[1]"></div>


$('div[name=name[1]]'); //errado?
$('div[name="name[1]"]'); //correto?
$('div[name="name\[1\]"]'); //correto?
$('div[name=name\[1\]]'); //correto?
asked by anonymous 12.12.2013 / 16:36

1 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.  


  • does not need to be shielded with the $('div[name="name[1]"]') escape.

  • name[1] , works, but does not need \ . JQuery reads the $('div[name="name\[1\]"]') selector as a string because it is inside quotation marks, and in javascript the backslash causes the second bar to be ignored \ resulting in name\[1\] , which in turn is the same as \ . So this example has backslashes unnecessarily.

From the jQuery documentation:


To use any of the following \[ metacharacters as part of a name, they must be shielded with two backslashes, leading bars: \\.

Example here

More reading (in English):

12.12.2013 / 16:36