Categories
interview

Implement getElementById() polyfill

Implement a method to search for an element in DOM by it’s Id. We use Breadth First Search (BFS) algorithm to traverse the DOM and store the elements in a queue in the following example.
Example: document.getElementById(‘demo’)

<div id="demo">
  <div>1</div>
  <div>2</div>
  <div>
    <div id="hello">Hello world!</div>
  </div>
  <div>3</div>
</div>
<script>
const getElementById = (element, id) => {
  const queue = [element];
  while (queue.length) {
    const curr = queue.shift();
    if (curr.id === id) {
      return curr;
    }
    if (curr.children.length) {
      queue.push(...curr.children);
    }
  }
};

console.log(getElementById(document.documentElement, 'hello').innerHTML); // Hello world!
</script>

Demo