javascript - custom querySelectorAll implemention -


this given me interview question -- didn't job, still want figure out.

the objective write 2 queryselectorall functions: 1 called qsa1 works selectors consisting of single tag name (e.g. div or span) , called qsa2 accepts arbitrarily nested tag selectors (such p span or ol li code).

i got first 1 enough, second 1 bit trickier.

i suspect that, in order handle variable number of selectors, proper solution might recursive, figured i'd try working iterative first. here's i've got far:

  qsa2 = function(node, selector) {     var selectors = selector.split(" ");     var matches;     var children;     var child;      var parents = node.getelementsbytagname(selectors[0]);     if (parents.length > 0) {         (var = 0; < parents.length; i++) {             children = parents[i].getelementsbytagname(selectors[1]);             if (children.length > 0) {                 (var = 0; < parents.length; i++) {                     child = children[i];                     matches.push(child); // somehow store our result here                 }             }         }     }     return matches;   } 

the first problem code, aside fact doesn't work, handles 2 selectors (but should able clear first, second, , fourth cases).

the second problem i'm having trouble returning correct result. know that, in qsa1, should returning same result i'd calling getelementsbytagname() function "returns live nodelist of elements given tag name". creating array , pushing or appending nodes isn't cutting it.

how compose proper return result?

(for context, full body of code can found here)

here's how i'd it

function qsa2(selector) {     var next = document;     selector.split(/\s+/g).foreach(function(sel) {         var arr = [];         (array.isarray(next) ? next : [next]).foreach(function(el) {             arr = arr.concat( [].slice.call(el.getelementsbytagname(sel) ));         });         next = arr;     });     return next; } 

assume start document context, split selector on spaces, you're doing, , iterate on tagnames.
on each iteration, overwrite outer next variable, , run loop again.
i've used array , concat store results in loop.

this similar code in question, should noted never create array, in fact matches variable undefined, , can't pushed to.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -