Build Your Own JavaScript DOM Library
About Lesson

 415 total views,  1 views today

Step 11: text() 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;
  }
  
  // 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
  }
  
  // todo:
  // 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;
  }
  
  function createNode(html) {
    let div = document.createElement('div');
    div.innerHTML = html;
    return div.firstChild;
  }
  
  window.Q = Q;
  
}(window));

Example => Step 11 => get/ set text()

Q(() => {
  test("Get text() method", function() {
    let t = Q(".completed");
    assert(true, t.text());
  });
  test("Set text(val) method", function() {
    let t = Q(".completed").text("This is completed!");
    assert(true, t.text());
  });
});
0% Complete