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

Asked

Viewed 1,328 times

12

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?
  • 7

    It’s fun to learn Portuguese here :) Square Bracket.

  • Now I was in doubt, straight relative is not correct (or correct :) in Portugal?

  • @bigown, I think that after last year’s orthographic agreement straight went straight... but since I’ve been living in the South for 5 years I still speak Portuguese "old" :)

  • "square bracket"

  • @Alexandrecartaxo then must be with "i" in parenthesesis? and should be "straight" or "straight"?

  • 1

    @Sergio "parentheses" and "parentheses" are synonymous. I use the spelling "straight" because I don’t write according to the spelling disagreement. By the way, it is "there" (from the verb "to be" and not "to", which is a contraction of a preposition with a definite article).

  • @Alexandrecartaxo ok :) an Edit is welcome!

  • @Sergio Not necessarily. As per AO90 is correct.

Show 3 more comments

1 answer

16


The first example $('div[name=name[1]]'); is incorrect, and gives the error unrecognized expression: div[name=name[1]].

The other options are correct, although for slightly different reasons.

Explanation:

  • $('div[name="name[1]"]') it’s okay to use because jQuery treatsname[1] as a string, since it is inside quotes, and not as a CSS/jQuery selector, and so does not need to be shielded with the exhaust \\.

  • $('div[name="name\\[1\\]"]'), works, but does not need to \\. jQuery reads the selector name\\[1\\] as a string because it is inside quotes, and in javascript the backslash causes the second bar to be ignored\ resulting in \[, which for your sake is the same as [. So this example has inverted bars without need.

  • $('div[name=name\\[1\\]]') it’s okay and internal right relatives [] have to be shielded with backslashes so as not to be confused with CSS/jQuery selectors.

From the jQuery documentation:

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

Example here


More reading (in English):

Browser other questions tagged

You are not signed in. Login or sign up in order to post.