document.querySelector("#id") 和 document.getElementById("id") 有什么区别吗?

2019-12-27 18:59:34 +08:00
 lisisi

1、看到一些 document.querySelector("#id") 的用法,这个新方法比 document.getElementById("id") 有什么优势吗?
2、遇到 id 是变量,document.querySelector("#id") 怎么传 id 进来呢?

const foo = 'id_Name';
document.querySelector("#" + foo)

试了下,上面这样写没效的

6539 次点击
所在节点    JavaScript
32 条回复
Danswerme
2019-12-27 19:18:06 +08:00
1. querySelector 接收一个 css 选择器字符串,比如 "#root > .nav:nth-child(1)",后者只能接收 id 名称。
2. 请检查你的代码
ysc3839
2019-12-27 19:20:07 +08:00
我觉得没有优势,因为要解析 css 选择器。
Cbdy
2019-12-27 19:22:56 +08:00
没有区别
stillsilly
2019-12-27 19:31:20 +08:00
有区别,不过我现在在外面没时间也没电脑,晚上回家没人回答的话我来解释一下
lisisi
2019-12-27 19:52:59 +08:00
@Danswerme document.getElementById("id") 中的 id 可以直接把变量传进来,document.querySelector("#id") 中的 id 并没有看到可用的传值方式。不知道你有没有明白我说的问题?
littlepanzh
2019-12-27 20:10:27 +08:00
现在的前端真幸福,不用考虑 IE6 7
noreplay
2019-12-27 21:36:23 +08:00
MDN 上有解释
https://developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementById

然而你的那个代码是有效的。
你可以打开控制台,试下下面的代码
const id="Wrapper";
document.querySelector('#'+id)
lxk11153
2019-12-27 21:36:56 +08:00
@Danswerme #1 对于问题 1,求深入点,内部实现呢?仅比较 getElementById("id")和 querySelector("#id"),内部会不会掉用到同一处实现呢?你这回答的太表象了,肉眼都能识别啊
@lisisi #5 对于问题 2,字符串拼接传咯?有什么问题?
429463267
2019-12-27 21:40:10 +08:00
你说的是 jsoup api ?
VDimos
2019-12-27 21:50:17 +08:00
这还新方法,这 api 不都好久了吗
netChen
2019-12-27 21:53:40 +08:00
还是楼上那句话,现在前端真幸福,不用考虑 IE6
autoxbc
2019-12-27 22:05:28 +08:00
从一致性上说,应该只使用 querySelector,其他元素选择方法一律弃用

不要考虑性能问题,这是引擎设计者应该考虑的,可维护性才是重点
lxk11153
2019-12-27 22:09:21 +08:00
@noreplay #7 之前还没注意,querySelector 有 2 个
- Document.getElementById()
- Document.querySelector() https://developer.mozilla.org/zh-CN/docs/Web/API/Document
- Element.querySelector() https://developer.mozilla.org/zh-CN/docs/Web/API/Element

So: document.querySelector("#id")和 document.getElementById("id")内部会不会调用到同一处实现呢?
vanishcode
2019-12-27 22:17:14 +08:00
一个是静态一个是动态
前者是后者的引用所以要慢一些
不知道是不是记错了。。。欢迎老哥指正。。。
Mutoo
2019-12-27 22:33:46 +08:00
@lxk11153 当然是同一个,因为 Document 和 Element 的 querySelector() 都是继承自 ParentNode.querySelector()
lxk11153
2019-12-27 23:09:07 +08:00
@Mutoo #15 感谢,文档还是没有源码细。。
Talk is cheap show me the code.
Code never lies, comments sometimes do.
zhlssg
2019-12-27 23:47:12 +08:00
querySelector 和 querySelector 可以代替 className, tagName, id 这些旧的 api,好记也是优点吧
zhlssg
2019-12-27 23:48:10 +08:00
@zhlssg querySelectorAll
secondwtq
2019-12-27 23:51:22 +08:00
#8 难道是楼主的小号 ...

用 querySelector + 字符串拼接意味着可以 query 的不只 id ... 在输入的字符串后面可以加其他选择器

@ysc3839 选择器只用解析一遍,有缓存
但是用来做同样的工作,前者是要稍微慢一点(因为确实包了一层)
geelaw
2019-12-28 00:05:52 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/632977

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX