There are many methods to get an element from the DOM. We will go from the slowest to fastest methods based on performance.
This is the fastest method to retrieve an object from the DOM. When an element is added to the DOM with an id, it is stored as a global variable in the document tree object. (You can find more about how that design choice happened here, it's a funny story!). This is also why DOM element IDs need to be unique. When you call this method passing the ID of the element you need as an argument it instantly refers this global store and returns the DOM object.
document.getElementsByTagName(); //using tag name document.getElementsByClassName(); //using class name
document.getElementsByTagName takes a HTML tag name (like
<div> etc) as an argument and returns elements having that HTML tag type.
document.getElementsByClassName takes a classname as an argument and returns elements having that classname. As the name suggests these two functions retrieve multiple DOM elements at once and hence perform slower than
document.querySelector(); //returns the first element document.querySelectorAll(); //returns all elements
These are very powerful functions to retrieve DOM elements. They take CSS selectors as an argument to retrieve the elements. This allows you to mix and match selectors to find the exact element(s) you need.
document.querySelector returns the first matched element, while
document.querySelectorAll returns all matched elements. As functionality and capability increases so does required time. Hence these are the slowest of the native DOM element retrieval functions.
jQuery is a very useful library of functions which makes it easier to query the DOM and traverse elements. It has a lot of built in functions to retrieve elements and manipulate them. It has the functionality of all the native functions and more, but the major drawback is the time required for every operation. jQuery is much more slower than native JS in doing equivalent tasks. You can find more about jQuery here.
In this post we have seen several different methods for accessing DOM elements using ID, tagName, className, selectors and by using jQuery. Hope you liked it. Thanks for reading through. <3