2
\$\begingroup\$

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:

<div></div>
<div id="idOne" class="classOne classTwo"></div>
<img id="IdTwo" class="classTwo classThree"></img>

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 < selectors.length; ++i) {
        arr.push(selectors[i].nodeName);
    }

    console.log(arr);

}
\$\endgroup\$
  • \$\begingroup\$ The way I understood the question return the parent DOM element is that given <div><img ...></div> and a selector img, it would need to return the <div>, i.e. its parent element. But with the given example DOM it wouldn't work (or would return whatever the surrounding element actually is, e.g. <body>). \$\endgroup\$ – morbusg May 14 at 15:12
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Yeah, I see the logic. But wouldn't that return all CSS selectors? Not the selectors that belong to one HTML element? EG, if I was given CSS selectors of img#idOne that should return an empty array, but if used with your algorithm, it would return true as all CSS selectors exist in the DOM \$\endgroup\$ – dumbquestionsbydumbpeople May 14 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.