16

How should I escape attributes in the css/js attibute selector [attr=value]?

Specifically, is this correct?

document.querySelector('input[name="test[33]"]')

I'm looking for the "standard way" of doing this, if any, because I don't want Sizzle using a heavy-to-execute fallback function

skyline26
  • 1,924
  • 4
  • 22
  • 34

1 Answers1

14

Yes, that is one correct approach. The Selectors Level 3 specification states the following:

Attribute values must be CSS identifiers or strings.

The example in your question uses a string as the attribute value. An "identifier" is defined as follows:

In CSS, identifiers... can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code...

So following that, it is also legal to escape the special characters and omit the quotes:

document.querySelector('input[name=test\\[33\\]]')
Bergi
  • 572,313
  • 128
  • 898
  • 1,281
James Allardice
  • 160,885
  • 21
  • 326
  • 309
  • @JamesAllardice is there any function (user-defined) to escape values? `document.querySelector('[name="' + escapeattr(value) + '"]')` thanks – skyline26 Dec 21 '12 at 11:26
  • 2
    @toPeerOrNotToPeer - Not that I know of, but you don't need to escape if you enclose the value in quotes, which is what I always do. – James Allardice Dec 21 '12 at 11:33
  • 1
    There is currently CSS.escape as a working draft for browsers for this solution without quotes. – David Gausmann Apr 06 '20 at 16:16
  • 1
    [`CSS.escape()`](https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape) is the recommended way of solving this and is supported by all modern browsers. Mathias Bynens has a [polyfill](https://github.com/mathiasbynens/CSS.escape/blob/master/css.escape.js) also. – Marc Durdin Jan 18 '21 at 21:46