How to properly escape attribute values in css/js attribute selector [attr=value]?
Asked Answered
S

3

18

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

Strategic answered 21/12, 2012 at 10:1 Comment(0)
F
12

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\\]]')
Fetter answered 21/12, 2012 at 10:4 Comment(4)
@JamesAllardice is there any function (user-defined) to escape values? document.querySelector('[name="' + escapeattr(value) + '"]') thanksStrategic
@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.Fetter
There is currently CSS.escape as a working draft for browsers for this solution without quotes.Abe
CSS.escape() is the recommended way of solving this and is supported by all modern browsers. Mathias Bynens has a polyfill also.Evaleen
S
3

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).

Spalato answered 7/7, 2023 at 23:21 Comment(1)
This needs to be the top answer.Isobath
B
-2

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

Barabbas answered 16/8, 2023 at 15:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.