+ 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

6th Nov 2019, 5:51 AM
ASM
ASM - avatar
6 ответов
+ 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
7th Nov 2019, 9:29 AM
Gordon
Gordon - avatar
+ 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 😄😄😄❤❤
6th Nov 2019, 1:31 PM
ASM
ASM - avatar
+ 7
Gordon Thank You So much for this brilliant answer and the links, You Rock 🌟🌟🌟
7th Nov 2019, 10:48 AM
ASM
ASM - avatar
7th Nov 2019, 9:43 AM
Gordon
Gordon - avatar
+ 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.
6th Nov 2019, 8:45 AM
marjel101
marjel101 - avatar
+ 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.
6th Nov 2019, 10:36 AM
Joyce Bissa
Joyce Bissa - avatar