Build Your Own JavaScript DOM Library
About Lesson

Step 5: Add support for ID, class selector

function (window, undefined) {
  // todo: changed code
  let domReadyQueue = [];  // FIFO
  
  // Define a ready handler
  const handleDOMReady = (fn) => {
    return document.readyState === "complete"
      ? fn.call(document)
      : domReadyQueue.push(fn);
  }
  
  document.addEventListener("DOMContentLoaded", function onDOMReady() {
    document.removeEventListener("DOMContentLoaded", onDOMReady); 
    while(domReadyQueue.length) {
      domReadyQueue.shift().call(document);
    }
  })
    
  function Q (selector) {
    
    this.nodes = [];  // array to store query results
    
    if (!(this instanceof Q)) {
      return new q(selector);
    }
    if (typeof selector === "function") {
      return handleDOMReady(selector);
    }
    
    // todo: changed code
    this.nodes = [].slice.call(document.querySelectorAll(selector));
    
  } 
  window.Q = Q;
}(window));

We use the document.querySelectorAll method (in case all standard CSS3 selectors). So, this one method is quite sufficient to meet most of our query requirements.

Example: Step 5 => Let’s test the code

Q(() => {
  let $byId = Q("#tasks");
  let $byClass = Q(".critical");
  
  test("Query by selectors", function() {
    assert($byId.nodes.length == 1, "1 node found");
    assert($byClass.nodes.length == 2, "2 nodes found");
  });
});
0% Complete