knowledge
  • Nature of the DOM
  • DOM node operation
  • DOM structure manipulation
  • DOM performance

preface

There are a lot of different frameworks, but DOM manipulation will always be the foundation of the front-end engineer’s knowledge.

Front-end programmers who only know Vue and React frameworks and don’t understand DOM manipulation…

The nature of DOM?

Do you know?

First, let’s look at what XML is. The code:

<? The XML version = "1.0" encoding = "ISO - 8859-1"? > <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting! </body> </note>Copy the code

EXtensible Markup Language XML

XML is a markup language designed to transmit and store data, not display it (HTML was designed to display data)

XML uses tags that are not predefined; you need to define your own tags.

SGML, HTML, XML, XHTML, HTML5 relationships, okay?

HTML is a special kind of XML. It follows W3C rules, all sorts of rules about what you have to write first and how you write it.

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <div> <p> Follow W3C standards, eat your lunch... Remember, ( ̄▽ ̄) Blue </p> </div> </body> </ HTML >Copy the code

So if it’s a string object (a big chunk of HTML), let the browser, JS processing is very inconvenient. How to query, how to operate and so on more troublesome. So when the browser gets the code…

DOM can be understood as the browser takes the HTML code, structure a browser can recognize and JS can manipulate a model (DOM structure tree)

I don’t want to talk about tree structure, do I

DOM node operation

Get DOM node

  • To operate with methods of element type:
  1. 支那document.getElementById();// The class id is used only at the top level. You can’t rely too much on id

    支那
  2. 支那document.getElementsByTagName();/ / tag name

    支那
  3. 支那document.getElementsByClassName();/ / the name of the class

    支那
  4. 支那document.getElementsByName();// Name attribute value

    支那
  5. 支那document.querySelector();// CSS selector pattern, returns the first element matching the pattern, the result is an element; If no matching element is found, null is returned

    支那
  6. 支那document.querySelectorAll()// CSS selector pattern, returns all elements matching the pattern, the result is an array of classes

    支那

Note:

  • The prefix is document, which means you can call these methods on the Document node, but you can also call them on other element nodes.
  • querySelector()andquerySelectorAll()Both methods are static, not real-time, saving the state at that time, is a copy, that is: in the future code through the method to change the selected element, but the value still does not change, so the use of limitations, generally not, unless you want to get a copy

  • Get nodes according to the relationship tree (traversing the node tree) :

We already know that the DOM (Document Object Model) can represent any HTML or XML document as a multi-level tree of nodes. All pages represent a tree structure with a particular node as the root node. The root node of an HTML document is the document node.

All nodes have the nodeType attribute, which represents different types of nodes. You can use the nodeType attribute to determine the nodeType.

Commonly used nodes are of the following types:

  1. Element type (Element node) : the nodeType value is 1
  2. Text type (Text node) : the nodeType value is 3
  3. Comment type (Comment node) : The nodeType value is 8
  4. Document type (Document node) : nodeType is 9

Some of the common attributes specified are:

  • document.body document.headRespectively in HTML<body> <head>
  • document.documentElementfor<html>The label

All nodes have the hasChildNodes() method, which returns true if one or more children exist

A node tree can be traversed by several attributes:

  1. parentNode// Get the parent of the selected node. The topmost node is #document
  2. childNodes// Get the children of the selected node
  3. firstChild// Gets the first child of the selected node
  4. lastChild// Gets the last child of the selected node
  5. nextSibling// Gets the last node in the list of siblings of the selected nodenextSiblingAttribute values fornull
  6. 'previousSibling' // gets the 'previousSibling' attribute of the first node in the previousSibling list of the selected node as' null '

Note: Due to the large number of node types in the document, traversing child nodes often does not yield the desired results. Be careful!! Empty text is also a text node! It is convenient to traverse element nodes.

  • Traversal based on element node tree (traversal element node tree) :
  1. parentElement// Returns the parent node of the current element (not compatible with IE9 below)
  2. children// Returns the element child node of the current element
  3. firstElementChild// Returns the first element child node (not compatible with IE9)
  4. lastElementChild// Returns the last element child node (IE9 is incompatible below)
  5. nextElementSibling// Returns the next sibling element node (IE9 is not compatible below)
  6. previousElementSibling// Returns the previous sibling element node (not compatible with IE9)

Note: These methods of retrieving nodes return either a specific node or a collection HTMLCollection, which is an array of classes.

Attributes in HTML and properties in JavaScript

attribute

** Attribute is an attribute defined in an HTML tag (modifying an HTML attribute changes the HTML structure), and its value can only be a string. Attribute has three methods: setAttribute(), getAttribute(), and removeAttribute() **

property

Property is a property that JavaScript defines for an element object (modifying an object property is not reflected in the HTML structure). Property properties can be thought of as key-value pairs of DOM objects, and are modified using the dot operator. It can also add custom properties and methods just like any other JavaScript object. The value of the property can be any data type and is case sensitive.

Attribute Indicates the attribute that is jointly owned by the property and property

Attribute and Property define attributes at different levels, but the following attributes are shared: ID class lang dir title

<div id="div" class="class" lang="lang" dir="dir" title="title" user="user" >


 var ele = document.getElementById('id');
 
 console.log(ele.getAttribute('id'))    // id
 console.log(ele.getAttribute('class')) // class
 console.log(ele.getAttribute('lang'))  // lang
 console.log(ele.getAttribute('dir'))   // ltr
 console.log(ele.getAttribute('title')) // title
 console.log(ele.getAttribute('user'))  // user

 ele.user1= 'user1'
 console.log(ele.id)                    // id
 console.log(ele.className)             // class
 console.log(ele.lang)                  // lang
 console.log(ele.dir)                   // ltr
 console.log(ele.title)                 // title
 console.log(ele.user1)                 // user

 console.log(ele.user)                  // undefined
 console.log(ele.getAttribute('user1')) // null
Copy the code

Custom properties do not appear in HTML code, only in JS. Therefore, el.getAttribute (‘ user1 ‘) results in: null

There are five standard features of HTML tags: ID, title, lang, DIR, className (these features are synchronized to the HTML tag when operating with property in the DOM). So even if id, title, and so on are not specified in HTML, an empty string is given by default, accessible through the property attribute (dot operator). Other attributes set in HTML are not accessible through Property (except attributes that are specific to the attribute). Therefore, the result of ele. User is: undefined

Note: There are some special cases:

– input Specifies the value of the element

var input1 = document.getElementById('input1'); // Get input element input1.setAttribute('value', 'test') with id 'input1'; // Use setAttribute() to set the value attribute to 'test' console.log(input1.value); // test a.value = 'change'; // Property sets value console.log(a.getattribute ('value')); // testCopy the code

Modifying a value with the dot operator is not synchronized to the attribute. But using setAttribute to change the value of the property will be synchronized to the property.

– the form

<input type='radio' checked='checked' id='radio'>
<script>
  var radio = document.getElementById('radio');
  console.log(radio.getAttribute('checked')); // 'check'
  console.log(radio.checked); // true
</script>
Copy the code

For some form elements, as long as these special attribute nodes exist, the corresponding property is true, similar to disabled

– href

<a href='a.html' id='web'> </a> <script> var radio = document.getElementById('web'); console.log(web.getAttribute('href')); // 'a.html' console.log(web.href); // absolute path </script>Copy the code

Attribute fetch is a relative path; Property is an absolute path.

Advice:

Use property as much as possible, because property can avoid DOM re-rendering in some JS mechanisms, and attribute changes to THE HTML structure will definitely cause DOM re-rendering.

Attribute is used in the following two cases:

  1. Customize the attribute tag because it cannot be synchronized to the property.
  2. Access attributes for built-in HTML tags, such as the value of the input (which can be used to check if the value has changed)

DOM structure manipulation

  • A node is added or inserted
  • Gets the list of child elements, gets the parent element
  • Deleting child elements

All kinds of DOM manipulation, please readers free play, play up yo ~~ must remember to knock more!!

Example: The main code is as follows

< div id = "div1" class = "container" > < p id = "p1" > section 1 < / p > < p > a paragraph 2 < / p > < p > a paragraph 3 < / p > < / div > < div id = "div2" > < img src="https://img-blog.csdnimg.cn/20200201200740869.jpg"/> </div> const div1 = document.getElementById('div1') const div2 = document.getelementById ('div2') // Create new node const newP = document.createElement('p') newp.innerhtml = 'this is newP' // Div1.appendchild (newP) // Move const p1 = document.getelementById ('p1') div2.appendChild(p1) // Get console.log( ParentNode) // Get the list of child elements const div1ChildNodes = div1.childNodes console.log(div1.childNodes) const div1ChildNodesP =  Array.prototype.slice.call(div1.childNodes).filter(child => { if (child.nodeType === 1) { return true } return false }) Log ('div1ChildNodesP', div1ChildNodesP) // removeChild elements div1.removechild (div1ChildNodesP[0])Copy the code

DOM performance

DOM manipulation is “expensive”, so avoid frequent DOM manipulation.

  • Cache DOM queries

    For (let = 0; i < document.getElementsByTagName(‘p’).length; I++) {}

    / / cache the DOM query results const pList = document. The getElementsByTagName () ‘p’ const length = pList. Length for (let I = 0; i < length; I++) {// cache length, only one DOM query}

  • Change the frequent operation to a one-time operation

    const list = document.getElementById(‘list’)

    / / create a document fragment, at this time has not yet been inserted into the DOM structure of const frag = document. CreateDocumentFragment ()

    for (let i = 0; i < 20; i++) { const li = document.createElement(‘li’) li.innerHTML = List item ${i}

    // Insert frag.appendChild(li)Copy the code

    }

    // Insert the list. AppendChild (frag) into the DOM.

    console.log(list)

Review and

What kind of data structure is DOM

  • Tree (DOM tree)

Common apis for DOM manipulation

  • DOM node operation
  • DOM structure manipulation
  • Attribute and property operations

Attribute and Property

  • Attribute: Modifying HTML attributes changes the HTML structure
  • Property: Modifies the attributes of an object, which are not reflected in the HTML structure
  • Both have the potential to cause DOM re-rendering

Insert multiple DOM nodes at once for performance reasons

  • You can flip it up and look again