使用 querySelector 而不是 document.getElementById
using querySelector instead of document.getElementById
我应该用document.querySelector
替换document.getElementById
左右吗?有什么区别吗?
你会推荐我使用querySelector
吗?
无论如何,当您选择 id 时,请使用 getElementById
,因为这比在 id 选择器上使用 querySelector
要高效得多。后者运行整个CSS选择器解析,而前者可以只获取ID并直接获取具有该ID的元素。
当然,当根据元素 id 以外的其他标准进行选择时,querySelector
(和querySelectorAll
)显然有它的位置。
(证明这一说法的强制性基准,尽管我确实想指出,基准并不是一切,而且差异在实际应用中可能不会产生太大差异。
两者在您的情况下具有相同的目的。但getElementById
是最行之有效的方法。但是,如果您不担心旧版浏览器,那么querySelector
也就足够了。
享受!
如果用户使用的浏览器中querySelector
可用。然后你可以使用它。不必用 id 乱扔你的 html 是件好事。使用 css 选择器进行选择非常灵活。
性能是一条红鲱鱼。我那糟糕的旧笔记本电脑每秒可以管理300万个选择......
真正的问题是兼容性。您将如何处理不可用的浏览器?你在乎吗?你可能不得不关心。
相关文章:
- 正在寻找比$(document).ready慢的$(window).load的替代方案
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 如何用更合适的内容替换document.write
- document.styleSheets不返回任何内容
- jQuery document.ready not working
- $(document).height()在刷新时随机化值(Safari 5.1.10)
- reactjs this.refs vs document.getElementById
- 如何通过adf中的document.getElementById获取inputText字段值
- window.opener.document在ie中不起作用
- contentWindow.document.body is null
- document.applet.method在Mounatin Lion上抛出safari 6+JDK7异常
- document.getElementById(“st”).click();不起作用
- $(document).height和$(window).heaght都返回相同的值-使用的是正确的doctype
- jQuery document.ready停止代码
- document.getElementById并使用id名称
- 使用jQuery 1.8.1准备好多个$(document).是否有任何开销
- document.getElementById在js中不起作用
- document.getElementById.style.backgroundImage not working
- 停止对document.ready函数的重定向/刷新
- 是否可以 document.getElementsByTagName('head')[0] ever 返回 null