Why does JS code “var a = document.querySelector(&

2019-03-09 15:29发布

I've an element in the DOM:

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

I want to get this element via its HTML5 custom data attribute data-a. So I write JS codes:

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

But this code doesn't work and I get an error in browser's console. (I tested Chrome and Firefox.)

JS code var a = document.querySelector('a[data-a=a]'); doesn't cause error. So I think the problem is that HTML5's JS API document.querySelector doesn't support to look for the number value in HTML5 custom data attribute.

Is this a problem of browser implementation bug or a problem of HTML5's spec relevant to document.querySelector?

Then I tested codes below on http://validator.w3.org/:

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

They're validated. Since these HTML5 codes are validated. We should can use HTML5's JS API document.querySelector to look for this anchor element via its custom data attribute. But tha fact is that I get error.

Does HTML5's spec to HTML5 JS API document.querySelector say that this method can not look for an HTML5 data custom attribute with a number value? (An HTML5 spec source is wanted.)

4条回答
聊天终结者
2楼-- · 2019-03-09 15:54

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"]');
查看更多
Deceive 欺骗
3楼-- · 2019-03-09 15:59

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

do JavaScript "document.querySelector('span[" & attrName & "=\"" & attrValue & "\"]').click();"
查看更多
三岁会撩人
4楼-- · 2019-03-09 16:01

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.

查看更多
5楼-- · 2019-03-09 16:02

You could use

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

instead of

var a = document.querySelector('a[data-a=1]');
查看更多
登录 后发表回答