为什么 JS 代码“ var a = document.querySelector (‘ a [ data-a = 1]’)”会导致错误?

我在 DOM 中有一个元素:

<a href="#" data-a="1">Link</a>

我想通过它的 HTML5自定义数据属性 data-a获得这个元素:

var a = document.querySelector('a[data-a=1]');

但是这个代码不起作用,我在浏览器的控制台中得到了一个错误(我测试了 Chrome 和 Firefox)

JS 代码 var a = document.querySelector('a[data-a=a]');不会导致错误。所以我认为问题在于 HTML5的 JS API document.querySelector不支持在 HTML5自定义数据属性中查找数值。

这是浏览器实现错误的问题,还是与 document.querySelector相关的 HTML5规范的问题?

然后我在 http://validator.w3.org/上测试了以下代码:

<!DOCTYPE html>
<meta charset="utf-8">
<title>An HTML Document</title>
<a href="#" data-a="1">Link</a>

它们是有效的。因为这些 HTML5代码是有效的。我们应该使用 HTML5的 JSAPIdocument.querySelector通过其自定义数据属性来查找这个锚元素。但事实是,我得到了错误。

HTML5对 HTML5 JS API document.querySelector的规范是否说明这种方法不能查找带有数值的 HTML5数据自定义属性?(需要一个 HTML5规范源代码。)

163194 次浏览

From the selectors specification:

Attribute values must be CSS identifiers or strings.

Identifiers cannot start with a number. Strings must be quoted.

1 is therefore neither a valid identifier nor a string.

Use "1" (which is a string) instead.

var a = document.querySelector('a[data-a="1"]');

You could use

var a = document.querySelector('a[data-a="1"]');

instead of

var a = document.querySelector('a[data-a=1]');

Yes strings must be quoted and in some cases like in applescript, quotes must be escaped

do JavaScript "document.querySelector('span[" & attrName & "=\"" & attrValue & "\"]').click();"

Took me a while to find this out but if you a number stored in a variable, say x and you want to select it, use

document.querySelector('a[data-a= + CSS.escape(x) + ']').

This is due to some attribute naming specifications that I'm not yet very familiar with. Hope this will help someone.

An example with variable (ES6):

const item = document.querySelector([data-itemid="${id}"]);

Because you need parentheses around the value your looking for. So here : document.querySelector('a[data-a="1"]')

If you don't know in advance the value but is looking for it via variable you can use template literals :

Say we have divs with data-price

<div data-price="99">My okay price</div>
<div data-price="100">My too expensive price</div>

We want to find an element but with the number that someone chose (so we don't know it):

// User chose 99
let chosenNumber = 99
document.querySelector(`[data-price="${chosenNumber}"]`)