Question

Try to execute this 2 code blocks in error console:

First one. Outputs NodeList.

var selector = "*[data-type=day][data-day='23']";
var a = document.querySelectorAll( selector );
alert( a );

Second one. Generates error.

var selector = "*[data-type=day][data-day=23]";
var a = document.querySelectorAll( selector );
alert( a );

Why data-type=day is ok syntax and data-day=23 is not? Should attribute values always be wrapped as data-type='day'?

Here is the exception, which raises in second case:

[Exception... "An invalid or illegal string was specified" code: "12" nsresult: "0x8053000c (SyntaxError)" ]

Was it helpful?

Solution

The browser is just following the specification which says:

Attribute values must be CSS identifiers or strings.

and on identifiers:

In CSS, identifiers (including element names, classes, and IDs in selectors) 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

So 23 (which starts with a digit) must expressed as a string:

Strings can either be written with double quotes or with single quotes

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top