如何修复不被接受为查询选择器的ID

How to fix an ID which isn't accepted as a query selector?

本文关键字:查询 选择器 ID 何修复      更新时间:2023-09-26

以下代码返回控制台错误:

"未捕获的语法错误:在'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