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,994
  • 4
  • 23
  • 35

3 Answers3

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
  • 630,263
  • 148
  • 957
  • 1,375
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • @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
  • 6
    [`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
0

Use CSS.escape() . One benefit of using this is that it works with variables, not just string literals:

el = document.querySelector('input[name="' + CSS.escape(name) + '"]');

It's supported in all modern browsers (caniuse).

Flimm
  • 136,138
  • 45
  • 251
  • 267
0

use apo next level backslash+apo next level ThreeBackslash+apo

$('mycard:has(\' mydiv:contains(\\\'Im a Hero\\\')\')')

CSS.escape will just create neutral text and you probably want to create nested selectors

sorry it also does not work correctly try mix quotes and apos

Medi
  • 1
  • 1