Difference between Nodes and Element Nodes

The official explanation

In the HTML DOM (Document Object Model), each part is a node:

  • The document itself is the document node
  • All HTML elements are element nodes
  • All HTML attributes are attribute nodes
  • Text inside an HTML element is a text node (including carriage returns)
  • Comments are comment nodes

An Element object can have child nodes of type Element node, text node, comment node.

The NodeList object represents a list of nodes, such as a collection of children of HTML elements.

Elements can also have attributes. Properties are property nodes.

Summary: An element is an element node, a kind of node, but an element node can contain many nodes.

His conclusion

Dom document is a collection of hierarchical nodes. Each node can have its own parent/child node. The nodes are typed, including document node, comment node, element node, attribute node and text node.

So an Element is a type of node. The Node Node can be regarded as the base class. Element inherits the base class and has Node’s attribute methods.

High frequency attribute method

Commonly used Document method

methods describe
createComment(data) Creates a new Comment node with the specified string
createElement(tagName[, options]) Creates a new Element node with the specified tag name
createTextNode(data) Creates a new TextNode node with the specified text
getElementId(id) Returns the Element node in the document with the specified ID attribute
getElementByTagName(tagName) Returns all Element nodes in the document with the specified tag name

The sample

// Get the element by ID
var elem = document.getElementById('id');

// Get the element by the tag name
var allParas = document.getElementsByTagName("p");

// Create the element
let newDiv = document.createElement("div");

// Comment the node
var comment = docu.createComment('This is the comment.');
newDiv.appendChild(comment);

// Text node
let newContent = document.createTextNode("Hi there and greetings!");
// Add a text node to the new div element
newDiv.appendChild(newContent);
Copy the code

Common Node properties and methods

attribute describe
childNodes Holds the children of the current Node as Node[], or returns an empty array if there are no nodes
firstChild Returns the first Node of the current Node as Node, or NULL if there is no Node
lastChild Returns the last Node of the current Node as Node, or NULL if there is no Node
parentNode Returns the parent Node of the current Node as Node or NULL if there is no Node
nodeName The Element node represents the name of the Element tag
nodeType Represents the type of the node
methods describe
appendChild(aChild) Add nodes to the document tree by adding a node to the current node’s childNode[] group
cloneNode(deep) Copies the current node, or the current node and all of its descendants
hasChildNodes() Returns true if the current node has children
insertBefore(newNode, referenceNode) Inserts a node into the document tree before the specified location of the current node, deletes it if it already exists, and then inserts the node into its location.
removeChild(child) Deletes from the document tree and returns the specified child
replaceChild(newChild, oldChild) Removes and returns the specified child from the document tree, replacing it with another node.

The sample

// Create a new paragraph element 

and add it to the end of

var p = document.createElement("p"); document.body.appendChild(p); var dupNode = node.cloneNode(deep); // node // The node to be cloned // dupNode // Clone the generated copy node / / deep is optional If true, all descendants of the node will be cloned. If false, only the node itself will be cloned. var p = document.getElementById("para1"), var p_prime = p.cloneNode(true); // If the element with id foo has child nodes, its first child node is removed from the DOM tree var foo = document.getElementById("foo"); if ( foo.hasChildNodes() ) { foo.removeChild( foo.childNodes[0]); }var insertedNode = parentNode.insertBefore(newNode, referenceNode); // insertedNode is inserted into the node (newNode) // parentNode parentNode of the new node // newNode specifies the node to be inserted // referenceNode newNode will be inserted before this node // If the referenceNode is null, newNode will be inserted at the end of the child node. let oldChild = node.removeChild(child); parentNode.replaceChild(newChild, oldChild); // newChild // Replace oldChild with a new node. If the node already exists in the DOM tree, it is first removed from its original location. // oldChild // The original node to be replaced. Copy the code

Common attributes and methods of Element

attribute describe
tagName Returns the value of the specified attribute as a string
innerHTML Returns the HTML code that this element contains, readable and writable
className Returns the class property of the current element, readable and writable
style Returns the inline style of the element nodeThe read/write
methods describe
addEventListener(type, listener, options) Add a callback function for the event
removeEventListener(type, listener[, options]) Remove the event listener function
dispatchEvent() Triggering event
preventDefault() Prevents default click events from executing
setAttribute() Sets the specified property to the specified string value, or adds a new property if it does not exist

Browser event capture, bubbling

The process in the browser event model is divided into three phases: capture phase, target phase, and bubble phase.

parent.addEventListener("click".function (e) {
    // e.stopPropagation(); No more events are sent. Termination events propagate further in the capture, target processing, or bubbling phases of the propagation process. When this method is called, the handler that handles the event on that node is called, and the event is no longer dispatched to another node.

    // e.target.nodeName refers to the currently clicked element. E.currenttarge. nodeName binds the element that listens for the event
    console.log("The parent trap", e.target.nodeName, e.currentTarget.nodeName);
}, true);
Copy the code

AddEventListener (type, listener, options) the third parameter

Note that the third argument to addEventListener, if true, is executed in the capture phase. If false, it is in the bubbling phase.

Preventing an event from spreading

  • e.stopPropagation()

One of the things you hear a lot about is preventing bubbling, but this actually prevents not only bubbling, but also the propagation of the capture phase.

  • stopImmediatePropagation()

If there are multiple event listeners of the same type of event bound to the same element, when events of that type are fired, they are executed in the order in which they were added. If one monitor function performs the event stopImmediatePropagation () method, which is the rest of the current element to monitor function will not be executed.

Blocking default behavior

  • e.preventDefault()

You can prevent the default behavior of events, such as clicking the A TAB to jump to another page, dragging an image to the browser to open automatically, clicking the submit button on a form to submit a form, etc., because sometimes we don’t want these things to happen, so we need to prevent the default behavior

The way events are delegated

<! DOCTYPEhtml>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <ul id="ul">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
            <li>8</li>
        </ul>
    </body>
    <script type="text/javascript">
        const ul = document.querySelector("ul");
        ul.addEventListener('click'.function (e) {
            const target = e.target;
          if (target.tagName.toLowerCase() === "li") {
            const liList = this.querySelectorAll("li");
            index = Array.prototype.indexOf.call(liList, target);
            alert(` content for${target.innerHTML}, the index for${index}`); }})</script>
</html>


Copy the code

compatibility

AttachEvent — Compatible with IE7 and IE8; The third parameter is not supported to control which phase occurs, the default is to bind addEventListener in bubbling phase — compatible with: Firefox, Chrome, IE, Safari, Opera;

Browser-compatible binding event functions

class BomEvent {
    constructor(element) {
        this.element = element;
    }

    addEvent(type, handler) {
        if (this.element.addEventListener) {
            // Event type, function to execute, whether to capture
            this.element.addEventListener(type, handler, false);
        } else if (this.element.attachEvent) {
            this.element.attachEvent('on' + type, function () {
                handler.call(element);
            });
        } else {
            this.element['on'+ type] = handler; }}removeEvent(type, handler) {
        if (this.element.removeEnentListener) {
            this.element.removeEnentListener(type, handler, false);
        } else if (element.datachEvent) {
            this.element.detachEvent('on' + type, handler);
        } else {
            this.element['on' + type] = null; }}}// Prevent events (mainly event bubbling, since IE does not support event capture)
function stopPropagation(ev) {
    if (ev.stopPropagation) {
        ev.stopPropagation(); / / the w3c standards
    } else {
        ev.cancelBubble = true; // IE}}// Cancel the default behavior of the event
function preventDefault(event) {
    if (event.preventDefault) {
        event.preventDefault(); / / the w3c standards
    } else {
        event.returnValue = false; // IE}}Copy the code

Event loop

Get to know how JS works at once

Problem summary:

  • Processes and threads
  • Why is JS single threaded
  • Know the browser
  • Event loop
  • Macrotask & MicroTask
  • Running mechanism in NodeJS

Asynchrony and event loops