06. Create element dynamically

 277 total views,  1 views today

Let’s now add the method to create element dynamically.

Step 6: Create element
(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);
    }
    
    // todo: 
    if (typeof selector === 'string') {
      // create element
      if (selector[0] === '<' && selector[selector.length-1] === '>') {
        this.nodes = [createNode(selector)];
      } else {
        this.nodes = [].slice.call(document.querySelectorAll(selector));
      }
    }
  } // END - Q
  
  // todo
  function createNode(html) {
    let div = document.createElement('div');
    div.innerHTML = html;
    return div.firstChild;
  }
  
  window.Q = Q;
  
}(window));

Let’s take a look at the important code block.

 if (typeof selector === 'string') {
      // create element
      if (selector[0] === '<' && selector[selector.length-1] === '>') {
        this.nodes = [createNode(selector)];
      } else {
        this.nodes = [].slice.call(document.querySelectorAll(selector));
      }
 }

Breakdown of logical steps

  • If the type of selector is string (for e.g. Q(“<div>”)
    • if the first charater is ‘<‘ and the last character is ‘>’
      • We use a helper method createNode to create a new node and store it in the array
    • else
      • We simply use the querySelectorAll method

Here is the createNode function.

function createNode(html) {
    let div = document.createElement('div');
    div.innerHTML = html;
    return div.firstChild;
  }

Breakdown of Logical steps

A quick and dirty way to create DOM element using string

  • Create a div element
  • Set the innerHTML to the content
  • Return the div element’s firstChild

Example => Step 6 => Create element

Let’s test our code.

Q(() => {
  test("Create element with string", function() {
    let div = Q("<div>New element</div>");
    let divWithAttrs = Q("<p id='p1'>This is a paragraph</p>");
    assert(div.nodes[0] instanceof HTMLElement, "<div/> created");
    assert(divWithAttrs.nodes[0] instanceof HTMLElement, "<p/> created");
  });
});