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.
- If user provides both attribute and value then match if node has attribute with specific value
- If user provide only attribute then return all nodes which have that attribute
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
var traverseDOM = function(node, fn) { fn(node); node = node.firstChild; while(node) { traverseDOM(node, fn); node = node.nextSibling; } } var getElementByAttr = function(attr, val) { var result = []; traverseDOM(document.body, function(node){ var valid = node.nodeType===1 && node.getAttribute(attr); if(typeof valid === 'string' &&(valid===val || typeof val !== 'string')) { result.push(node); } }); return result; }; console.log(getElementByAttr('class', 'test')); |
Things to note in getElementByAttribute
- nodeType===1 is used to to determine if it is an element node. For more details, pls refer – Node Types
- 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.
- node.nextSiblind and node.first child are properties of a node. Please check – nextSibling