Handwritten DOM library

Because the DOM native API is too hard to use

Source code link

Object style

  • Window.dom is the global object we provide

Add node

  • dom.append(parent,child)  // Used to add a son node
    Copy the code
  • dom.wrap(`<div></div>`)   // To add a parent node
    Copy the code

The dom. The create function

dom.create(`<div><span>hi</span></div>`) // Used to create a node
Copy the code
  • The point of creating a node is to insert it into other nodes,
  • So I’m going to encapsulate one for inputHTMLThe create function
  • The ability to create nodes while adding other nodes
  • The string is passed in as HTML with tags

Dom. Create the source code

create(string) {
    // Create a container template tag that can hold any element
    const container = document.createElement('template')
    // trim to prevent null characters
    container.innerHTML = string.trim()
    // You must use.content otherwise you can't get it
    return container.content.firstChild

    / / or
    // container.innerHTML = string
    // return container.content.children[0]
  }
Copy the code

The sample

const div = dom.create('<div><span>hello</span></div>')
console.log(div);
Copy the code

Dom. After the function

Because of the API in the DOM, it’s hard to insert a node after a node because there’s only a way to add the previous node

dom.after(node,newNode)     // To add the next node
Copy the code

Dom. After the source code

There is no need to worry about what happens if node is the last node. Even if it’s null, it can still be inserted

 after(node, newNode) {
    // Find the parent of the node and call insertBefore,
    // Insert newNode before the next node
    return node.parentNode.insertBefore(newNode, node.nextSibling)
  }
Copy the code

The sample

Dom. Before function

This method is the same as the dom.after method,

dom.before(node,node2)   // Used to add a new node
Copy the code

Dom. Before the source code

before(node, newNode) {
    // Return the DOM native method of adding the previous node
    return node.parentNode.insertBefore(newNode, Node)
  }
Copy the code

Dom. Append function

dom.append(parent,child)  // Used to add a son node
Copy the code

Dom. Append the source code

  append(parent, node) {
    return parent.appendChild(node)
  }
Copy the code

Dom. Wrap function

Move the node out of the DOM tree, insert the parent node in its place, and then insert the parent node into the parent node

dom.wrap(`<div></div>`)   // Use to add a node (parent) node around this node
Copy the code

Dom. Wrap the source code

  wrap(node, newNode) {
    // Place newNode before and after node
    dom.before(node, newNode)
    // Then put the node node inside the newNode
    dom.append(newNode, node)
  }
Copy the code

Realization idea diagram:

Example:

Remove nodes

  • dom.remove(node) // Used to delete a node
    Copy the code
  • dom.empty(parent)  // Used to delete offspring
    Copy the code

The dom. The remove function

Usage: Delete a node and return the node

Let his father delete his son.

The source code

  remove(node) {
    node.parentNode.removeChild(node)
    // Returns the deleted node
    return node
   }
Copy the code

The dom. The empty function

Usage: Remove all children of this node

Iterate over all of its children and return the deleted node

Why we can’t use the for loop: Because every time dom.remove is removed, its length changes, and we loop through it, I tested a bug, so we chose to use the while loop.

The source code

  empty(node) {
    const firstChild = node.firstChild
    while (firstChild) { 
      array.push(dom.remove(node.firstChild))
    }
    // Returns the deleted node
    return array
  }
Copy the code

The sample

Modify the

Modify the

  • dom.attr(node,'title'.'hello')  // Change the title property of node to hello for reading and writing properties,,
    dom.attr(node,'title')  // Get the title property of the node
    Copy the code
  • dom.text(node,'I'm modified.')  // Change the text in node to XXXXX for reading and writing text
    dom.text(node)   // View the text
    Copy the code
  • dom.html(node,' I am modified ')  // Change the HTML element content in node to XXXX, which is used to read and write HTML content
    dom.html(node)  // View the HTML content in this node
    Copy the code
  •   dom.style(node,{color:'red'})   // Use to modify the style
    Copy the code
  • dom.class.add(node,'btn')  // Used to add the class name
    Copy the code
  • dom.class.remove(node,'btn')   // Used to delete class
    Copy the code
  • dom.class.has(node,'btn')  // Check to see if you have a class name
    Copy the code
  • dom.on(node,'click',fn) // Used to add event listeners
    Copy the code
  • dom.off(node,'click',fn)  // Used to delete event listeners
    Copy the code

Dom. Attr function

Usage: Sets/modifies the property value and property name in this node if three arguments are passed

dom.attr(node,'title'.'hello')		// If you pass in three parameters, set its attribute name and value
dom.attr(node,'title')    // Get the attribute name if two arguments are passed
Copy the code

The source code

  attr(node, name, value) {
    if (arguments.length === 3) {
      // Sets an attribute and its value
      node.setAttribute(name, value)
    } else if (arguments.length === 2) {
      // View the value of an attribute of this node
      return node.getAttribute(name)
    }
  }
Copy the code

The sample

Dom. Text function

Use the same as innerText

The source code

  text(node, string) {
    if (arguments.length === 2) {   / / overloaded
      if ('innerText' in node) {  / /
        node.innerText = string
      } else {
        node.textContent = string
      }
    } else if (arguments.length === 1) {
      if ('innerText' in node) {
        return node.innerText
      } else {
        return node.textContent
      }
    }
  }
Copy the code

The sample

The dom HTML function

Use the same as innerHTML

The source code

 html(node, string) {
    if (arguments.length === 2) {
      node.innerHTML = string
    } else if (arguments.length === 1) {
      return node.innerHTML
    }
  }
Copy the code

Dom. Style function

The native DOM manipulation style is written as follows:

 xxx.style.color = 'red'Or XXX. Style ['color']  = 'red'  
Copy the code

I encapsulated the style of writing:

dom.style(xxx,{color:'red'})
Copy the code

Style [key], where color is a variable that needs to be retrieved from the object we pass in. The reason you don’t use style.color=’red’ is because the object’s attribute value is a string.

The source code

style(node, object) {
    for (let key in object) {
      // we cannot use style.key because key is a variable
      node.style[key] = object[key]
    }
  }
Copy the code

The sample

Use the form of an object to modify the style:

Make the string form to modify the style

The dom. The class function

Usage:

dom.class.add(test, 'red')   // Add the class name
dom.class.remove(test, 'red')   // Delete the class name
console.log(dom.class.has(test, 'red'));   // Check the class name
Copy the code

Start by creating three different methods in the class object. Then encapsulate the native DOM.

The source code

  class: {
    add(node, className) {
      node.classList.add(className)
    },
    remove(node, className) {
      node.classList.remove(className)
    },
    has(node, className) {
      return node.classList.contains(className)
    }
  }
Copy the code

The sample

The dom.on and dom.off functions

Usage:

dom.on(test, 'click', fn)  // fn is the function that adds the click event
dom.off(test,'click',fn) // Remove the click event
Copy the code

Encapsulate the native DOM addEventListener.

The source code

 on(node, eventName, fn) {
    node.addEventListener(eventName,fn)
  },
  off(node, eventName, fn) { 
    node.removeEventListener(eventName,fn)
  }
Copy the code

The sample

Search (get elements)

  • dom.find('selector')  // Used to get tags or tags
    Copy the code
  • dom.parent(node)  // Used to get the parent element
    Copy the code
  • dom.children(node)  // Used to get child elements
    Copy the code
  • dom.siblings(node)  // Used to get sibling elements
    Copy the code
  • dom.next(node)  // To get the younger brother
    Copy the code
  • dom.previous(node)  // Get the older brother
    Copy the code
  • dom.each(nodes,fn)  // Used to traverse all nodes
    Copy the code
  • dom.index(node)  // Get the element with index value x
    Copy the code

The dom. The find function

Usage and the document. QuerySelectorAll ()

The source code

 find(selector) {
    return document.querySelectorAll(selector)
  }
Copy the code

Example:

The dom.parent function and the dom.children function

Usage:

dom.parent(node)  // Used to get the parent element
dom.children(node)  // Used to get child elements
Copy the code

The source code

 parent(node) {
    return node.parentNode
  },
      
  children(node) {
    return node.children
   }
Copy the code

Dom. Siblings function

Usage:

dom.siblings(node)  // Use to get sibling elements (other than yourself)
Copy the code

Parentnode. children: get all the children of node.parentNode.children: get all the children of node.parentNode.children: get all the children of node.parentNode.children: get all the children of node.parentNode.children

The source code

  siblings(node) {
    return Array.from(node.parentNode.children)
      .filter(n= >n ! == node) }Copy the code

Dom. parent, dom.children, and DOM.siblings examples

Dom.next and dom.previous functions

Usage:

dom.next(node)  // Used to get the next node (brother) node
dom.previous(node)   // Used to get the previous node (elder) node
Copy the code

We use node.nextSibing to return a text node, we need to exclude the text node (nodeType 1 is an element node, nodeType 3 is a text node), the same as dom.previous

The source code

 next(node) {
    let x = node.nextSibling
    while (x && x.nodeType === 3) { // 1 is the element node, 3 is the text node
      x = x.nextSibling
    }
    return x
  },
  previous(node) {
    let x = node.previousSibling
    while (x && x.nodeType === 3) { // 1 is the element node, 3 is the text node
      x = x.previousSibling
    }
    return x
  }
Copy the code

The sample

Dom. Each function

Usage: Iterate over each element to make it do the corresponding thing

dom.each(nodes,fn)  // Used to traverse all nodes
Copy the code

The source code

  each(nodeList, fn) {
    for (let i = 0; i < nodeList.length; i++) {
      fn.call(null, nodeList[i])
    }
  }
Copy the code

Example:

The dom. The index function

Usage: Returns the index value of the current node in the parent node

dom.index(node)  // Returns the index of the current node in its parent node
Copy the code

Get all the children of your parent node, then iterate, if the child is you, return I

The source code

  index(node) {
    const list = dom.children(node.parentNode)
    for (let i = 0; i < list.length; i++) {
      if (list[i] === node) {
        return i
      }
    }
  }
Copy the code

Example: