4

What is the difference between these different ways to escape square brackets inside jQuery selectors.

Is there a right or wrong way or are these both correct? I have read different answers (including this) but none compare this different ways.

HTML

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

jQuery

$('div[name=name[1]]'); //wrong
$('div[name="name[1]"]'); //correct?
$('div[name="name\\[1\\]"]'); //correct?
$('div[name=name\\[1\\]]'); //correct?

All those I ask correct? work, is that ok way/syntax to use the selector?

EDIT :

I read the duplicate suggested answer before I posted actually and it does not explain the differences or which should be used... I got that now from this answer.

Community
  • 1
  • 1
Rikard
  • 7,485
  • 11
  • 55
  • 92

2 Answers2

7

Apart from the first wrong case: $('div[name=name[1]]'); which throws a error unrecognized expression: div[name=name[1]] - all other are ok to use, because of slightly different reasons.

Explanation:

  • $('div[name="name[1]"]') is ok to use because jQuery treats name[1] as a string and not a CSS/jQuery selector. So no need to escape it.

  • $('div[name="name\\[1\\]"]'), is actually unnecessary escaped, but works. jQuery reads name\\[1\\] as a string, and in javascript the first backslash \ escape the second which results \[, and this is the same as [. So this example is the same as the previous with unnecessary backslashes.

  • $('div[name=name\\[1\\]]') is ok and the inner [] are escaped as they should so they will not be confused as CSS/jQuery selectors.

From the jQuery documentation:

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



Demo here

Good to read:

Sergio
  • 28,539
  • 11
  • 85
  • 132
0

try something like this

        var div = document.getElementsByName('name[1]')[0];
        //now use your own way
        $(div).text();
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40