+ 14
What is the difference between document.getElementById/tagName/Class And document. querySelector
Events listener are used to modify contents of an element with reference to elements Id, ClassName, Tagname but why do we use querySelector, querySelectorAll , what is its purpose, pros and cons
6 Answers
+ 6
A. Short answer
dynamic vs static
B. Your mistake
...ByClassName() and ...ByTagName() returns a group of elements, so there is a 's' in function name.
getElementsByClassName()
getElementsByTagName()
C. Singular versus group
Returns single element :
getElementById()
querySelector()
Returns a "group" of element :
getElementsByClassName()
getElementsByTagName()
querySelectorAll()
To access each element in the returned "group", you have to use index, e. g.
elementGroup[2]
D. HTMLCollection vs NodeList
getElements... returns a HTMLCollection, you can view it as storing a query, and execute it every call. When an element fulfilling the query gets deleted, your won't have trouble with encountering error or null with HTMLCollection.
querySelectorAll returns a NodeList, it stores reference to each element. When an element fulfilling the query gets deleted, your will run into error or null with NodeList.
https://code.sololearn.com/WKKkpq0efxai/?ref=app
+ 8
marjel101 RĂ©gy Joyce Bissa Mintyene Okk So basically getElementbyId,... works as specific selectors while QuerySelector simply acts as a global selector, Thanks Guyss đđđâ€â€
+ 7
Gordon Thank You So much for this brilliant answer and the links, You Rock đđđ
+ 6
(continue due to word limit exceed)
E. Reference
for part C
https://www.sololearn.com/post/94559/?ref=app
for part D
https://www.sololearn.com/post/97036/?ref=app
https://code.sololearn.com/WKKkpq0efxai/?ref=app
+ 2
They both do the same, so thereâs no real difference that i know of.
Personally i prefer querySelector over getElementById/ClassName etc, because you can use the normal CSS rules when referring to an element, with an # for idâs and a dot for classes etc.
+ 1
The difference is, if you want to access to an element using his id or his name or his class, you must use document.getElementById/TagName/Class respectively. But that is annoying, so you can just use document.querySelector to access to an element either by his id or his name or his class.