Searching for selectors not using document.querySelector/document.querySelectorAll I had a technical interview the other day and failed a certain question:


  
    Given a CSS selector (can just be a class name, id or an arbitrary
    number of selectors), return the parent DOM element in an array. The caveat is that you cannot use external libraries or use
    document.querySelector or document.querySelectorAll. Use
    the HTML code below:
  

&lt;div&gt;&lt;/div&gt;
&lt;div id="idOne" class="classOne classTwo"&gt;&lt;/div&gt;
&lt;img id="IdTwo" class="classTwo classThree"&gt;&lt;/img&gt;



For example, if given a CSS selector of img.ClassTwo it would return the img tag, where if the given CSS selector was div#idOne.classTwo it would return 1 div, whereas if the selector was just div, it would return 2 divs. Whereas if I was given img#One it would return an empty array.

My code below works, but I feel that it is too 'cheeky' as it doesn't use either document.querySelector or document.querySelectorAll directly, but uses a variation of document.querySelectorAll - as I can't think of an alternative method that can cater for an arbitrary number of CSS selectors unlike how document.querySelector or document.querySelectorAll can.

Is my code correct? Or can it be improved anyway?

var theFunction = function (input) {

    let arr = [];

    let body = document.getElementsByTagName("BODY")[0];

    let selectors = body.querySelectorAll(input);

    for (i = 0; i &lt; selectors.length; ++i) {
        arr.push(selectors[i].nodeName);
    }

    console.log(arr);

}
Your method doesn't work because it fails to select elements outside the body.

I think what you were supposed to do is:


split the input into class / ID / tagName (using REGEX or whatever)
request elements using document.getElementByID() / document.getElementsByClassName() / document.getElementsByTagName() 
return only the elements that match all 3 requests.


Essentially, you code your own querySelectorAll function.