本文介绍了JavaScript中的querySelector和querySelectorAll vs getElementsByClassName和getElementById的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 querySelector querySelectorAll 之间究竟有什么区别? getElementsByClassName getElementById

来自我可以用 querySelector收集它我可以写 document.querySelector(。myclass)获取类 myclass 文档的元素.querySelector(#myid)获取ID myid 的元素。但我已经可以做到 getElementsByClassName getElementById 。应该首选哪一个?

From this link I could gather that with querySelector I can write document.querySelector(".myclass") to get elements with class myclass and document.querySelector("#myid") to get element with ID myid. But I can already do that getElementsByClassName and getElementById. Which one should be preferred?

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

Also I work in XPages where the ID is dynamically generated with colon and looks like this view:_id1:inputText1. So when I write document.querySelector("#view:_id1:inputText1") it doesn't work. But writing document.getElementById("view:_id1:inputText1") works. Any ideas why?

推荐答案

语法和浏览器支持。

querySelector 在您想要使用更复杂的选择器时更有用。

querySelector is more useful when you want to use more complex selectors.

例如所有列表项都来自作为foo类成员的元素: .foo li

e.g. All list items descended from an element that is a member of the foo class: .foo li

字符在选择器中有特殊含义。你必须逃脱它。 (选择器转义字符在JS字符串中也有特殊含义,所以你必须转义那个)。

The : character has special meaning inside a selector. You have to escape it. (The selector escape character has special meaning in a JS string too, so you have to escape that too).

document.querySelector("#view\\:_id1\\:inputText1")

这篇关于JavaScript中的querySelector和querySelectorAll vs getElementsByClassName和getElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 02:14