DEV Community

Discussion on: Enough JavaScript to get you Started : #14 Understanding DOM

Collapse
 
derobpe profile image
DĂ©bora Robles PĂ©rez

The captures to show the index and app code for:

  • getElementById
  • getElementsByClassName
  • querySelector Looks identical to me. Not sure if they should be different though. Regards!
Thread Thread
 
whoadarshpandya profile image
Adarsh Pandya

In a way they're same, cause they fall under category of selecting node/element from the dom.

But they give different performance under different circumstances , you can check performance here : https://measurethat.net/Benchmarks/Show/1144/1/getelementbyid-vs-queryselector-vs-getelementsbyclassna
Enter fullscreen mode Exit fullscreen mode

getElementbyId() is useful when you target particular id from the DOM, which returns single element

getElementsByClassName() or getElementByTagName() will return list of matched elements according to what is passed as parameter , there for i used [0] in getElementByClassName() , both methods returns list of elements

While querySelector() is useful to peek class/id/tag by prefixing their css notation (i.e) id root can be #root and class active can be .active, we can also pass tag names here but in all case querySelector() returns only first element and not list of elements , if you want list of elements to be selected querySelectorAll() can be useful

Regards.