DEV Community

Cover image for JavaScript Basics : How to retrieve an element from the DOM?
Athul Anil Kumar
Athul Anil Kumar

Posted on

JavaScript Basics : How to retrieve an element from the DOM?

JavaScript can do many wonderful things, and one of them is DOM (Document Object Model) manipulation. To manipulate a DOM element you need to access the corresponding DOM object and that is what this post is all about. Lets get right into it.


Needle in a Haystack

There are many methods to get an element from the DOM. We will go from the slowest to fastest methods based on performance.

Accessing By ID

document.getElementByID();

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.

Accessing by Class Name or Tag Name

document.getElementsByTagName();    //using tag name
document.getElementsByClassName();  //using class name

document.getElementsByTagName takes a HTML tag name (like <p>,<a>,<span>,<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.getElementByID.

Accessing using Selectors

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.

Bonus Method : Accessing using jQuery

jQuery(selector);
jQuery.find(selector);

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.


Conclusion

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

Top comments (0)