10. Implementing html() method to get and set HTML dynamically

 281 total views,  2 views today

Step 10: html() method

(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
    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
  
  // Get the prototype (jquery trick)
  Q.fn = Q.prototype;
  
  Q.fn.each = function (callback) {
    for(let i = 0; i < this.length; i++) {
      callback.call(this, this[i], i);
    }
    return this;
  }
  
  // todo
  Q.fn.html = function (val) {
    console.log("html", val);
    if (val == undefined) {
      return this[0].innerHTML;
    }
    console.log("this: ", this);
    this.each((e) => {
      e.innerHTML = val;
    });
    
    return this; // todo : for chaining
  }
  
  function createNode(html) {
    let div = document.createElement('div');
    div.innerHTML = html;
    return div.firstChild;
  }
  
  window.Q = Q;
  
}(window));

Example => Step 10 => html()

Q(() => {
  test("Get html() method", function() {
    let $ul = Q(".critical");
    assert(true, $ul.html());
  });
  
  test("Set html(val) method", function() {
    //callback.call(this[i], this, i);
    let html = Q(".critical").html("<b>New values</b>");
    assert(true, html.html());
  });
});