querySelector-当id为数字开头时

40 阅读1分钟

背景

生成的随机id 可能含有数字开头的

问题

当 id 为数字时 比如 2aYAq3OZBSIg

使用 document.querySelector('2aYAq3OZBSIg') 会报错

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': '#2aYAq3OZBSIg' is not a valid selector.
    at <anonymous>:1:26

解决办法

  1. 使用 document.getElementById

  2. 使用 document.querySelector(#${CSS.escape(id)}) 进行转义 转义过后会变成 \\32 aYAq3OZBSIg

  3. 使用属性选择器 document.querySelector('[id="2aYAq3OZBSIg"]')

ts

document.querySelect 的 ts类型为 Element 还包括 (svg xml)

document.getElementById 的 ts 类型为 HTMLElement

类型继承关系如下 HTMLElement ==extends==> Element ==extends==> Node ==extends==> EventTarget