Introduction of the DOM

A web page is a tree

How does JS manipulate this tree

The browser adds a Document to the window. JS uses the document to operate the web page. This is the Document Object Model.

API

Get elements, also known as tags

There are a lot of API

Window. Idxxx // or directly idxxx, the simplest method, But sometimes there will be a conflict document. GetElementByld (' idxxx) document. The getElementsByTagName (' div ') [0] Document. GetElementsByClassName () 'red' [0] / / complex document not commonly used by these three methods. The querySelector (' # idxxx ') / / attention to add # # Document. QuerySelectorAll (' red ') [0] / / the two methods are commonly usedCopy the code

Get specific elements

Getting HTML elements

document.ducumentElement

Get the head element

document.head

Get the body element

document.body

Get Windows (Windows are not elements)

window

Get all elements

document.all

Document. All is the invention of IE, is the sixth Falsy value.

A 6-level prototype chain of elements

The element we get is an object, so we need to figure out its prototype.

Console. dir(div1) look at the prototype chain —

Level 1 prototype

HTMLDivElement. Prototype. This is a common attribute for all divs.

Layer 2 prototype

Htmlelement. prototype, which is a common attribute for all HTML tags.

Level 3 prototype

Element.prototype, which is a common attribute for all XML/HTML tags (browsers display more than HTML)

Level 4 Prototype

Node.prototype, this is a common attribute for all nodes, including XML tag text comments, HTML tag text comments, etc.

Level 5 prototype

Eventtarget. prototype, the most important function property is addEvenListener

Level 6 prototype

Object.prototype

node

The difference between nodes and elements

The Node? Element?

Nodes NODES include the following types, including Element

MDN is fully described, x.nodetype gets a number.

Add, delete, change and check nodes

increase
  • Create a label node

    let div1 = document.createElement('div')
    document.createElement('style')
    document.createElement('script')
    document.createElement('li')
    Copy the code
  • Create a text node

    text1 = document.createTextnode('hello')
    Copy the code
  • Insert text inside the tag

    div1.appendChild(text1)
    div1.innerText='hello'Or div1. TextContent ='hello'
    Div1.appenchild (' hello ') cannot be used
    Copy the code
  • Insert into the page

    The tag created by default is in the JS thread and must be inserted into the head, the latter, and the body for it to take effect.

    document.body.appendChild(div)

    or

    Element already in the page. AppendChild (div)

The appendChild topic

There are div#test1 and div#test2 in the pagelet div = document.createElemnt('div')
test1.appendChild(div)
test2.appendChild(div)
Copy the code

Where does the final div appear?

In test2, an element cannot appear in two places at the same time unless a copy is made.

delete
  • The two methods

    Parentnode.removechild (childNode)

    New method: childNode.remove() // Ie does not support this method

  • thinking

    If a Node is removed from the page (DOM tree), can it be returned to the page again?

    You can.

    How do I delete a node?

    div = null

change
  • Change attributes

    • Modified standard attributes

      • Change id

        div1.id = 'div1'
        Copy the code
      • To change the class

        Div1. Class is a JS reserved word
        div1.className = 'blue'	Div1. ClassName += 'red'
        div1.classList.add('green')	//class = "blue red green"
        Copy the code
      • Change a style

        div1.style = 'width: 100px; color: blue; '
        div1.style.width = '200px'	// Change part of the style
        Copy the code

        When changes are similar to background – color that have crossed the attributes, rewrite for div1. Style. The backgroundColor can perform.

      • Change data – * attributes

        div1.dataset.x='river'
        Copy the code
    • Read standard attributes

      Div. ClassList/a.href div. GetAttribute ('class')/a.gett attribute ('href') // Either method works, but the values may be slightly differentCopy the code
  • Change the time handler function

    • Div. onclick defaults to null

      Clicking div by default does nothing

      But if you change div.onclick to a function fn, the browser will call that function when the div is clicked

      And fn.call(div,event)

      Div is called this, and event contains all information about the click event, such as coordinates

    • div.addEventListener

      Is an updated version of div.onclick

  • To change the content

    • Modify text content

      Div. InnerText = 'XXX' div. TextContent = 'XXX' // There is almost no difference between the twoCopy the code
    • To change the HTML content

      Div. InnerHTML = '<strong> Important content </strong>'Copy the code
    • To change the label

      Div. InnerHTML = "// Empty string, empty div. AppendChild (div2) // change the contentCopy the code
  • To my father

    newParent.appendChild(div)
    Copy the code
check
  • Look up dad

    Node. ParentNode or node. ParentElementCopy the code
  • Check the grandpa

    node.parentNode.parentNode
    Copy the code
  • Check the offspring

    Node. The.childnodes or node. The childrenCopy the code
    • First question:

      Console. log(test.childnodes.length) prints 7, which is text, li, text, li, text, li, text.

      Text is carriage return + space

      So the following print is 3

      Use children to avoid this. Use more children!!

    • Second question:

      Do both change in real time when the offspring change?

      It changes in real time.

      And document. QuerySelectorAll (” li “) will not change in real time

  • Brothers and Sisters

    Node. ParentNode..childnodes / / also ruled out own node parentNode. Children / / also ruled out yourselfCopy the code

    The first is to find the parent’s child, and the second is to traverse the array and exclude itself.

    Operation example:

    Div1’s parent has 35 children

    Get the siblings array by iterating through div1 itself side by side

  • To see the boss

    node.firstChild
    Copy the code
  • Look at last

    node.lastChild
    Copy the code
  • View previous older brother/sister

    Node. PreviousSibling / / node is likely to see the text node previousElementSiblingCopy the code
  • Check out the next sibling

    node.nextSibling
    node.nextElementSibling
    Copy the code
  • Iterate over all the elements in a div

    travel = (node,fn) => {
    	fn(node)
    	if(node.children){
    		for(let i = 0; i < node.children.length; i++){
    			travel(node.children[i],fn)
    		}
    	}
    }
    travel(div1,(node) => console.log(node))
    Copy the code

DOM operations are cross-threaded

Browser functions are divided into rendering engine and JS engine. The rendering engine is used to render HTML and CSS, and the JS engine operates JS.

Cross-thread operation

Each thread does its job

The JS engine cannot manipulate pages, only JS

Rendering engines cannot manipulate JS, only pages

The document. The body. The appendChild (div1) this sentence is how to change the page?

Cross-thread communication

When the browser finds that JS has added a div1 object to the body

The browser tells the rendering engine to add a new div element to the page as well

The new div element copies all the attributes of the DIV1 object

Note: one is an object and one is an element.

The complete process of inserting a new label

Before DIV1 goes into the page

All operations on DIV1 belong to the JS thread

When you put DIV1 on the page

When the browser discovers JS’s intent, it tells the render thread to render div1 elements in the page

Put div1 after the page

Anything you do to DIV1 can trigger a re-render

Div1.id =’newId’ may or may not be re-rendered

Div1.title =’new’ may or may not be re-rendered

If you perform multiple operations on div1 in a row, the browser may or may not merge into one operation, as in the following example. If you do not add test.clientWidth, JS will merge and the animation will not display by default.

Attribute synchronization

Standard properties

Standard property changes to DIV1 are synchronized to the page by the browser

Such as ID, className, title, etc

Data – * attributes

Same as above

Nonstandard attribute

Changes to non-standard attributes will only stay in the JS thread and will not be synchronized to the page

For example, the X property, sample code

revelation

If you have custom attributes that you want to synchronize to the page, use data- as a prefix

Property V.S. Attribute

The property attribute

All properties of div1 in the JS thread, called div1’s property

The attribute properties

The attribute that div1 corresponds to in the rendering engine is called an attribute

The difference between

Most of the time, property and attribute values with the same name are equal

But if it’s not a standard property, then it’s only going to be equal at the beginning

Note that attribute only supports strings

Property supports strings, booleans, and so on

What is encapsulation

For example,

Computer notebook is the PACKAGING of CPU, memory, hard disk, motherboard, graphics card, users only need to contact the display, keyboard, mouse, touch pad and other equipment, can operate a complex computer.

interface

Packaged things need to expose some functions to the outside, these functions are interfaces, such as USB interface, HDMI interface.

As long as the device supports these ports, it can communicate with encapsulated objects, such as a USB keyboard and mouse, and an HDMI monitor.

The term

library

We call the tool code that we provide to others libraries, such as JQuery, Underscore

API

The functions or properties that the library exposes are called apis

The framework

When a library becomes large and requires learning to understand, the library is a framework, such as Vue and React

DOM encapsulation

The source code