Created
February 28, 2016 07:56
-
-
Save itsanna/957da4cce2cf7724b341 to your computer and use it in GitHub Desktop.
reimplement getElementsByTagName
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
List of elements of type/ reimplement getElementsByTagName | |
* Returns a list of all elements of given type which are children of provided parent. | |
* @param {! string} `tagName` The tag name of the element. eg. 'DIV' | |
* @param {Node} `parent` The root node under which the search must be performed. | |
* @return {!Array} A list of elements of given type that are children of provided parent. Empty if none could be found. | |
*/ | |
var getElementsByTagName = function (tagName, parent) { | |
var elements = {} // tag name : element | |
var results = [] // array of elements | |
var root = parent || document | |
for (var i=0; i < root.all.length; i++) { | |
elements[root.all[i].tagName] = root.all[i] | |
} | |
for (var tag in elements) { | |
if (tag === tagName) { | |
results.push(elements[tagName]) | |
} | |
} | |
return results | |
} | |
var div = getElementsByTagName('DIV') | |
console.log(div) | |
// can't use document.all b/c it's not supported in all browsers. | |
// and because parent.all wouldn't work. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment