Implementation of getElementbyId()

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.

Syntax

getElementById(id)

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 (node.id === candidateId)return node;
    let arr = [];
    let explored = new Set();
    arr.push(node);

    explored.add(node);

    while (arr.length > 0){
        let temp = arr.shift();
        if (temp.id === 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">
    <head>
        <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>
    </head>
    <body id = "test">
        <div>
            <p>
                Hello There !!!
            </p>
        </div>
        /index.js
    </body>
</html>

Try it Out

Happy Learning

Subscribe to newsletter and receive latest tech updates .

Advertisements

Leave a Reply

Discover more from Chandan Rajpurohit

Subscribe now to keep reading and get access to the full archive.

Continue reading