Build Your Own JavaScript DOM Library
About Lesson

We want to access the results of query via “this” object.

(function (window, undefined) {
  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) {  // BEGIN q
    
    this.nodes = [];  // array to store query results
    
    if (!(this instanceof q)) {
      return new q(selector);
    }
    if (typeof selector === "function") {
      return handleDOMReady(selector);
    }
    
    if (typeof selector === 'string') {
      if (selector[0] === '<' && selector[selector.length-1] === '>') {
        this.nodes = [createNode(selector)];
      } else {
        this.nodes = [].slice.call(document.querySelectorAll(selector));
      }
    }
    
    // todo
    // Add nodes to instace of Q(this)
    if (this.nodes.length) {
      this.length = this.nodes.length;
      for(let i = 0; i < this.nodes.length; i++) {
        this[i] = this.nodes[i];
      }
    }
  } // END - Q
  
  function createNode(html) {
    let div = document.createElement('div');
    div.innerHTML = html;
    return div.firstChild;
  }
  
  window.Q = Q;
  
}(window));

The important code block

if (this.nodes.length) {
      this.length = this.nodes.length;
      for(let i = 0; i < this.nodes.length; i++) {
        this[i] = this.nodes[i];
      }
 }

Breakdown of Logical steps

  • If the nodes length is greater than 0
    • Store the length property
    • Loop through all elements
      • Store each element in the object this at index i.

Let’s test the code.

Example => Step 7 => Access nodes via “this”


Q(() => {
  test("Access element by 'this'", function() {
    let div = Q("<div>New element</div>");
    let divWithAttrs = Q("<p id='p1'>This is a paragraph</p>");
    assert(div[0] instanceof HTMLElement, "<div/> created");
    assert(divWithAttrs[0] instanceof HTMLElement, "<p/> created");
  });
});
0% Complete