Build Your Own JavaScript DOM Library
About Lesson

Step 8: Create HTML element using existing element/nodes

(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);
    }
    
    // HTMLElements and NodeLists are wrapped in nodes array
    // todo
    if (selector instanceof HTMLElement || selector instanceof NodeList) {
      this.nodes = selector.length > 1 ? [].slice.call(selector) : [selector];
    } else if (typeof selector === 'string') {
        if (selector[0] === '<' && selector[selector.length-1] === '>') {
          this.nodes = [createNode(selector)];
        } else {
          this.nodes = [].slice.call(document.querySelectorAll(selector));
        }
    }
    
    // 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));

Example => Step 8 => Create HTML nodes using HTMLElement

Q(() => {
  test("Create element", function() {
    let ul = Q("#tasks");
    let node = Q(ul[0]);
    console.log("node: ", node[0]);
    assert(ul[0] instanceof HTMLUListElement, "<ul> selected");
    assert(node[0]  instanceof HTMLElement, "node retrieved");
  });
});
0% Complete