DEV Community

Hassam Ali
Hassam Ali

Posted on

How to create your own getEelmentById

In this write up I am going to show how to create your getElementById function it will be similar to document.getElementById

So before we begin I want to clarify what document.getElementById does it. It is a function when called with a given id finds the DOM element which has same id as the one passed to the function. If there are multiple ids it then will return the first element. Before we begin writing our function let's quickly recap how DOM is structured and what are some useful methods which we can use.

DOM

In layman terms DOM stands for document object model it is a tree like representation of HTML element. so for example lets say we have following HTML:

<!DOCTYPE HTML>
<html>
<head>
  <title>Hello World</title>
</head>
<body>
  <h1> A quick brown fox jumps over the lazy dog </h1>
  <div>
    <h2>This is a h2</h2>
    <p>This is a paragraph</p>
    <article>This is a article</article>
  </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

For this HTML the DOM would be like this:
Alt Text
In the above image we can see all the DOM nodes for the HTML. There are different types of DOM nodes. You can see the list at MDN. The document.getElementId works on HTML element and HTML elements have nodeType of 1.

So first of all we need to get all the children of document.body we can do this by calling document.body.children, this method return HTMLCollection so we need to convert it into array now there are different ways via which we can do that but the simples one is simply used the spread operator eg [...root.children]. Now this array contains all the children of document.body.

Now we will iterate over array and during each iteration we will pick an item from the array and we will check if the id of the elements is equal to the id we are looking for, this can done by calling .id on the selected item. if id matches then we will return the item otherwise we will repeat the same process on all of the children of the current element. In computer science this type of algorithm is called Depth First Search.

const walkDOM = (root, elementId) => {
 let result = null;
 const elements = [...root.children];
 for (let element of elements) {
  if (element.id === elementId) return element;
  if (element.children.length && element.nodeType === 1) {
   result = walkDOM(element, elementId);
   if (result) return result;
  }
 }
 return result;
};
const getElementById = (elementId) => {
 return walkDOM(document.body, elementId);
};
Enter fullscreen mode Exit fullscreen mode

Please note that this is not a replacement for document.getElementById but a simple snippet showing how powerful and feature rich the DOM the API is and how far we can go in web development without knowing how these methods work.

Top comments (0)