Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 298
Rikard Avatar asked Mar 22 '23 13:03

Rikard


1 Answers

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:

  • MDN - Escaping characters
  • jQuery - Selectors
  • W3.org - Characters
like image 105
Sergio Avatar answered Apr 07 '23 15:04

Sergio