【问题标题】:Difference between using document.querySelector('#id') and document.getElementById('id')使用 document.querySelector('#id') 和 document.getElementById('id') 的区别
【发布时间】:2021-04-25 04:02:43
【问题描述】:

我是 javascript 的初学者,我看到很多人使用 document.querySelector('#id') 和一些人使用 document.getElementById('id') 来获取带有 id 的 html 元素。 请回答天气这些是相同的,否则我们必须以不同的方式使用它们。

【问题讨论】:

标签: javascript html


【解决方案1】:

当您使用 getElementById 分配变量时,您不必声明您正在文档中查找 id,因为它已经在方法的名称和功能中。但是,当您使用 querySelector 执行相同的操作时,您使用的是 CSS 选择器,因此您需要添加 # 以表示您正在寻找一个 id,这就是关键的区别。

const container = document.getElementById("container")

const banner = document.querySelector("#banner")

最初两者都做同样的事情。

【讨论】:

    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多