如何修复不被接受为查询选择器的ID
How to fix an ID which isn't accepted as a query selector?
以下代码返回控制台错误:
"未捕获的语法错误:在'Document'上执行'querySelector'失败:'#57acafcbdb4bc607922b834f'不是一个有效的选择器。"
HTML5不应该接受以数字开头的id吗?对于需要这种类型的id的情况,是否有解决方案?
<!DOCTYPE html>
<html>
<body>
<h2 id="57acafcbdb4bc607922b834f">A heading with class="example"</h2>
<p>A paragraph with class="example".</p>
<p>Click the button to add a background color to the first element in the document with class="example".</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.querySelector("#57acafcbdb4bc607922b834f").style.backgroundColor = "red";
}
</script>
</body>
</html>
以数字开头的id在HTML 5中确实是有效的,但是#57acafcbdb4bc607922b834f
不是一个有效的CSS选择器,而document.querySelector()
使用CSS选择器。
你可以使用属性选择器:
document.querySelector('[id="57acafcbdb4bc607922b834f"]')
或者您可以使用document.getElementById()
:
document.getElementById('57acafcbdb4bc607922b834f')
查看代码片段:
console.log(document.querySelector('[id="57acafcbdb4bc607922b834f"]'))
console.log(document.getElementById('57acafcbdb4bc607922b834f'))
<div id="57acafcbdb4bc607922b834f"></div>
// Escape the first digit with its unicode value in hex
document.querySelector('#''35 1').style.color = 'green'
// Or use getElementById
document.getElementById('52').style.color = 'red'
<div id="51"> Element 51, should be green </div>
<div id="52"> Element 52, should be red
来源:https://mothereff.in/css-escapes
相关文章:
- 未捕获的语法错误:无法在“文档”上执行“查询选择器”
- jQuery中的查询选择器导致无法识别的表达式
- j查询选择器不选择对象
- 事件冒泡与查询选择器
- 将查询选择器保存在要追加的变量中不起作用
- 不包含块引用的节点的查询选择器
- 查询选择器设置文本值
- 如何使用纯 Javascript 和文档查询选择器实现 jQuery .on() 函数
- 使用查询选择器查找同级行中包含的下一个单元格
- WebRTC文件传输和语法查询选择器
- 如何在聚合物中的自定义元素中成功查询选择器
- 聚合物查询选择器在聚合物元素中找不到自定义聚合物元素
- 更新的问题::查询选择器可能存在PhantomJS/Javascript问题
- 自定义查询选择器全部实现
- j查询选择器变量语法纠错
- j查询选择器无法正常工作
- IE8 查询选择器空值与正常空值
- 查询选择器全部不起作用
- Polymer.dom:dom元素的作用域查询选择器
- 如何使用查询选择器来选择常规短语