Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 954
skyline26 Avatar asked Dec 21 '12 10:12

skyline26


People also ask

How do I get attr in CSS?

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.

How do you use ATTR?

The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.

What CSS selector is used to select elements with a specified attribute and value?

CSS [attribute="value"] Selector The [attribute="value"] selector is used to select elements with a specified attribute and value.

When working with attribute selectors how can you select elements which contain a particular attribute value?

[attribute|=”value”] Selector: This selector is used to select all the elements whose attribute has a hyphen-separated list of values beginning with the specified value. The value has to be a whole word either alone or followed by a hyphen.


1 Answers

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\\]]')
like image 153
James Allardice Avatar answered Sep 30 '22 00:09

James Allardice