Javascript HTML .children traversal -


i'm trying go through of elements in document , pull ones target class name. importantly, i'm needing without use of document.getelementsbyclassname(classname) / document.queryselectorall, etc. — that's point of learning exercise.

here's javascript:

var getelementsbyclassname = function(classname){   var rootelem = document.body;   var collectionresult = [];   if (rootelem.getattribute("class") == classname) {     collectionresult.push(rootelem);   };   var nexttier = function(collectionresult, rootelem) {     var thistier = rootelem.children;     (i=0; i<thistier.length; i++) {       var classes = thistier[i].getattribute("class");       if (classes != undefined && classes.includes(classname)) {         collectionresult.push(thistier[i]);       };       var childrenarray = thistier[i].children;        if (childrenarray.length > 0) {         nexttier(collectionresult, childrenarray)       };     };   };   nexttier(collectionresult, rootelem);   return collectionresult; }; 

here's section of html structure i'm having trouble with:

<p>   <div class="somediv">     <div class="innerdiv">       <span class="targetclassname">yay</span>     </div>    </div>  </p> 

the code works rest of page number of non-nested elements. var childrenarray = thistier[i].children div.somediv element, has childrenarray == undefined rather pulling div.innerdiv element.

am misunderstanding how element.children works?

you seem overcomplicating things.

function getelementsbyclassname(classname, root) {   if(!root) root = document.documentelement;   return [].reduce.call(root.children, function(arr, child) {     if(child.classlist.contains(classname)) arr.push(child);     return arr.concat(getelementsbyclassname(classname, child))   }, []); } 

function getelementsbyclassname(classname, root) {    if(!root) root = document.documentelement;    return [].reduce.call(root.children, function(arr, child) {      if(child.classlist.contains(classname)) arr.push(child);      return arr.concat(getelementsbyclassname(classname, child))    }, []);  }  console.log(getelementsbyclassname("targetclassname"));
<div class="somediv targetclassname">    <div class="innerdiv">      <span class="targetclassname">yay1</span>    </div>  </div>  <div class="somediv targetclassname">    <div class="innerdiv targetclassname">      <span class="targetclassname">yay2</span>    </div>  </div>  <div class="somediv">    <div class="innerdiv">      <span class="targetclassname">yay3</span>    </div>  </div>


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -