Why we use root node. In below given function they use root node function. I want to understand this function also what is meaning of ‘!rootNode’.
function getElementsByClassName(cn, rootNode) {
if (!rootNode) {
rootNode = document;
}
for (var r=[], e=rootNode.getElementsByTagName('*'), i=e.length; i--;) {
if ((' '+e[i].className+' ').indexOf(' '+cn+' ')>-1) {
r.push(e[i]);
}
}
return r;
}
In your example,
rootNodeis the HTML element from which to start recursively searching the hierarchical DOM tree (which is how the web page is represented in JavaScript) for elements with class namecn.This allows the caller of your function to specify from where they want to search for elements with class name
cn. If the caller does not specifyrootNodethe function just returns every element in the entire web page with class namecn.The array
r=[]is initialised as an empty array into which the elements that are found get added (usingpush).i--is used because theforloop starts ati=e.length– the function goes through the elements returned bygetElementsByTagNamefrom the end of the array through to the start. Theforloop evaluates the result ofi--as a boolean, exitting whenihits-1(because on this iteration the boolean evaluation will have been done against the falue0, becausei--post-decrements the value ofi).