Custom getElementByAttribute function – JavaScript/FrontEnd interview question

This article will describe how you can write your own Custom getElementByAttribute function and it is a common JavaScript/FrontEnd interview question. It checks important web concepts  –

  • browser api usage of developer
  • closure in JavaScript
  • knowledge of tree data structure in DOM

We have to write a function -getElementByAttribute, which takes attribute and value and returns an array of elements based on these inputs.

  1. If user provides both attribute and value then match if node has attribute with specific value
  2. If user provide only attribute then return all nodes which have that attribute


Things to note in getElementByAttribute

  1. nodeType===1 is used to to determine if it is an element node. For more details, pls refer – Node Types
  2. because of closures, functions executed in traverseDOM has access to the result which enables us to write traverseDOM in a generic way. For example, we can use the same traverseDOM at other places, only change we have to do is to pass different function.
  3. node.nextSiblind and node.first child are properties of a node. Please check – nextSibling

Leave a Reply

Your email address will not be published. Required fields are marked *