Description
遇到的坑
当时传了一个uuid作为id值,发现使用 querySelector
去取该id时报错,用 getElementById
去取该id时却正常。
解决
getElementById
的限制
`The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.`
- ID必须唯一
- 至少包含一个字符
- 不能有空格符
- 可以仅由数字组成,以数字开头,以下划线开头,仅由标点符号组成,等等
querySelector
要符合CSS选择器标准
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, two hyphens, or a hyphen followed by a digit.
总结了大致要注意的几个点:
- 不能以纯数字开头
- 以连字符'-'开头时, 后面不能跟数字
不能有两个连字符- 只允许[a-zA-Z0-9]和连字符‘-’和下划线‘_’
e.g.
// html
<div id="1" class="1">id="1"</div>
<div id="_1" class="_1">id="_1"</div>
<div id="-1" class="-1">id="-1"</div>
<div id="__1" class="__1">id="__1"</div>
<div id="--1" class="--1">id="--1"</div>
<div id="_-1" class="_-1">id="_-1"</div>
<div id="-_1" class="-_1">id="-_1"</div>
<div id="_t1" class="_t1">id="_t1"</div>
<div id="-t1" class="-t1">id="-t1"</div>
<div id="_--1" class="_--1">id="_--1"</div>
<div id="_-t-1" class="_-t-1">id="_-t-1"</div>
// console
document.getElementById('xxx') 以上均能得到相应节点
document.querySelector('#1')
document.querySelector('#-1')
document.querySelector('#-t1')
以上报错:
VM3786:1 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#-1' is not a valid selector.
at <anonymous>:1:10
因为querySelector 要符合css选择器的标准, 因此
getElementByClassName
和querySelector('.xxx')同理
Activity