javascriptcss-selectorsselectors-api

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


In JavaScript, how should I escape attribute values for the CSS attibute selector [attr=value]?

Specifically, to match this element:

<input type="text" name="test[33]" />

is this correct?

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

Solution

  • 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\\]]')