Build Your Own JavaScript DOM Library
About Lesson

 397 total views,  1 views today

Step 12: Append html content to the end

(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;
  }
  
  // Get set HTML content
  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
  }
  
  // Get set text content of all matched element
  //   return the text content of first matched element
  Q.fn.text = function (str) {
    if (str) {
      return this.each(function (e) {
        e.innerText = str;
      })
    }
    return this.length && this[0].innerText;
  }
  
  // todo:
  // Append html content to the end
  Q.fn.append = function(html) {
    return this.each(function (e) {
      e.innerHTML = e.innerHTML + html;
    })
  }
  
  function createNode(html) {
    let div = document.createElement('div');
    div.innerHTML = html;
    return div.firstChild;
  }
  
  window.Q= Q;
  
}(window));

Example => Step 12-> append html content to the end

Q(() => {
  test("append html content to end", function() {
    let $ul = Q("#tasks");
    $ul.append("<li>Task 6</li>");
    let $li = Q("#tasks > li");
    assert($li.length == 6, "append: item added to end" );
  });
});
0% Complete