Naveen Naveen - 3 months ago 46
Javascript Question

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

I would like to know what exactly is the difference between

querySelector
and
querySelectorAll
against
getElementsByClassName
and
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?

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?

Answer

I would like to know what exactly is the difference between querySelector and querySelectorAll against getElementsByClassName and getElementById?

The syntax and the browser support.

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

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

document.querySelector("#view:_id1:inputText1") it doesn't work. But writing document.getElementById("view:_id1:inputText1") works. Any ideas why?

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")