getElementById() is common method used in HTML (Hyper Text Markup Language) DOM (Document Object Model).

getElementById() is used to fetch Element object with respect to id that matches the specified string in Document interface.



It returns specified element that matches to id passed else none if no matches found.

It is widely used while reading and editing/updating HTML object.

Here I am going to implement user defined getElementById() that performs basic task of getElementById() without using query selector.

For every page rendered HTML creates DOM which is basically a tree. We can use BFS(Breadth First Search) or DFS(Depth First Search) to implement getElementById().

console.log(document.children[0]); //root element
function getMyElementById(node,candidateId){
    if ( === candidateId)return node;
    let arr = [];
    let explored = new Set();


    while (arr.length > 0){
        let temp = arr.shift();
        if ( === candidateId) return temp;
        Array.from(temp.children).filter((n) => !explored.has(n)).forEach((n) => {explored.add(n);arr.push(n);}); 
console.log(getMyElementById(document.children[0],"test")); //getElementById("test")

Test Document

<!DOCTYPE html>
<html lang="en">
        <meta charset="UTF-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE-edge" />
        <meta name="viewport" content="width=device-width,initial-scale=1.0" />
        <title>Test Document</title>
    <body id = "test">
                Hello There !!!

Try it Out

Happy Learning

%d bloggers like this: