JavaScript中的querySelector和querySelectorAll

JavaScript中的querySelector和querySelectorAll vs getElementsByClassName和getElementById

我想知道究竟是什么之间的差异querySelectorquerySelectorAll对抗getElementsByClassNamegetElementById

这个链接我可以收集,querySelector我可以编写document.querySelector(".myclass")获取类的元素,myclassdocument.querySelector("#myid")获取ID元素myid。但我已经可以做到这一点getElementsByClassNamegetElementById。应该首选哪一个?

我也在XPage中工作,其中ID是用冒号动态生成的,看起来像这样view:_id1:inputText1。所以当我写document.querySelector("#view:_id1:inputText1")它不起作用。但写作document.getElementById("view:_id1:inputText1")有效。有什么想法吗?


泛舟湖上清波郎朗
浏览 1195回答 3
3回答

largeQ

querySelector和getlementbyID(Claassname,Tagname等)之间的主要区别在于,如果有多个元素满足条件,querySelector将只返回一个输出,而getElementBy *将返回所有元素。让我们考虑一个例子,使其更清晰。&nbsp;<nav id="primary" class="menu">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a class="link" href="#">For Business</a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a class="link" href="#">Become an Instructor</a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a class="link" href="#">Mobile Applications</a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a class="link" href="#">Support</a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a class="link" href="#">Help</a>&nbsp; &nbsp;</nav>&nbsp;下面的代码将解释差异**QUERY SELECTOR**document.querySelector('.link'); // Output : For Business (element)document.querySelectorAll('.link'); //Out All the element with class link**GET ELEMENT**document.getElementsByClassName('link') // Output : will return all the element with a class "link" but whereas in query selector it will return only one element which encounters first.如果我们想要为查询选择器选择单个元素,或者如果我们想要多个元素用于getElement,则为Inshort

牧羊人nacy

我想知道querySelector和querySelectorAll对getElementsByClassName和getElementById的区别究竟是什么?语法和浏览器支持。querySelector&nbsp;当您想要使用更复杂的选择器时更有用。例如,所有列表项都来自作为foo类成员的元素:&nbsp;.foo lidocument.querySelector(“#view:_id1:inputText1”)它不起作用。但是编写document.getElementById(“view:_id1:inputText1”)可以正常工作。有什么想法吗?该:字符有选择内部特殊的意义。你必须逃脱它。(选择器转义字符在JS字符串中也有特殊含义,所以你也必须转义它)。document.querySelector("#view\\:_id1\\:inputText1")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript