1 What is DOM

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It provides a structured representation of a document and defines a way for that structure to be accessed from within the program to change the structure, style, and content of the document. Document Object Model (DOM) is another way of presenting HTML files. In plain English, an HTML file can be presented as code in an editor or as a page in a browser. The same file can be presented in different ways. DOM, on the other hand, parses a document as a structured collection of nodes and objects (objects containing properties and methods). In short, it connects web pages to scripts or programming languages that can be used to change or control web pages through the DOM.

2 How do I access the DOM

We can use JavaScript to call the API of the Document and window elements to manipulate the document or retrieve information about the document.

3 Node

Node is an interface, and there are many interfaces that inherit methods and properties from Node: Document, Element, CharacterData (which Text, Comment, and CDATASection inherit), ProcessingInstruction, DocumentFragment, DocumentType, Notation, Entity, EntityReference. Node has a nodeType attribute, which is an integer. Different values represent different Node types. Details are shown in the following table:

Node type constant

constant value describe
Node.ELEMENT_NODE 1 An element node, for example<p><div>
Node.TEXT_NODE 3 ElementorAttrThe actual text in
Node.PROCESSING_INSTRUCTION_NODE 7 One for XML documentsProcessingInstruction, e.g.<? xml-stylesheet ... ? >The statement
Node.COMMENT_NODE 8 aCommentnode
Node.DOCUMENT_NODE 9 aDocumentnode
Node.DOCUMENT_TYPE_NODE 10 Describing the document typeDocumentTypeNode. For example,<! DOCTYPE html>It’s for HTML5
Node.DOCUMENT_FRAGMENT_NODE 11 aDocumentFragmentnode

Deprecated node type constant

constant value describe
Node.ATTRIBUTE_NODE 2 The coupling properties of the element. In the DOM4 specificationNodeThe interface will no longer implement this element attribute
Node.CDATA_SECTION_NODE 4 aCDATASection. Removed from the DOM4 specification
Node.ENTITY_REFERENCE_NODE 5 An XML entity refers to a node. Removed from the DOM4 specification
Node.ENTITY_NODE 6 An XML<! ENTITY ... >Node. Removed from the DOM4 specification
Node.NOTATION_NODE 12 An XML<! NOTATION ... >Node. Removed from the DOM4 specification

NodeType = 1 nodeType = 1 nodeType = 1

if(X.nodeType === 1) {console.log('X is an element ');
}
Copy the code

Among Node types, element, text, comment, document, and document_fragment are commonly used.

3.1 Element

Element provides access to Element tag names, child nodes, and attributes. Common HTML elements such as div, SPAN, and A tags are elements of this type. Element has the following characteristics: (1) nodeType is 1 (2) nodeName is the tagName of the Element, and tagName is the return tagName (3) nodeValue is null (4) parentNode may be Document or Element (5) child node may be Element, Text, Comment, Processing_Instruction, CDATASection or EntityReference

3.2 Text

Text represents the Text node, which contains plain Text content. It cannot contain HTML code, but can contain escaped HTML code. Text has the following features: (1) nodeType is 3 (2) nodeName is # Text (3) nodeValue is Text content (4) parentNode is an Element (5) Has no child nodes

3.3 Comment

Comment represents a Comment in an HTML document, which has the following characteristics: (1) nodeType is 8 (2) nodeName is #comment (3) nodeValue is the content of the comment (4) parentNode may be Document or Element (5) Has no child nodes

3.4 Document

Document stands for Document. In the browser, the Document object is an instance of HTMLDocument, representing the entire page. It is also a property of the Window object. Document has the following features: (1) nodeType is 9 (2) nodeName is # Document (3) nodeValue is null (4) parentNode is null (5) The child node may be a DocumentType or Element

3.5 DocumentFragment

DocumentFragment is the only type of node that does not have a corresponding tag. It represents a lightweight document and may serve as a temporary repository for nodes that might be added to the document. The DocumentFragment has the following features: (1) nodeType is 11 (2) nodeName is #document-fragment (3) nodeValue is null (4) parentNode is null

4 Node creation API

As the name suggests, this type of API is used to create nodes

4.1 createElement

CreateElement creates an element by passing in a specified tag name. If the passed tag name is unknown, a custom tag is created. Note: Custom tags are not supported in browsers below Internet Explorer 8.

grammar

  let element = document.createElement(tagName);
Copy the code

Note with createElement: The element created with createElement is not part of the HTML document; it is created and not added to the HTML document; it is added to the HTML document tree with a call like appendChild or insertBefore.

Example:

  let elem = document.createElement("div");
  elem.id = 'test';
  elem.style = 'color: red';
  elem.innerHTML = 'I'm a newly created node';
  document.body.appendChild(elem);
Copy the code

The running results are as follows:

4.2 createTextNode

CreateTextNode is used to create a text node

grammar

  var text = document.createTextNode(data);
Copy the code

CreateTextNode receives a parameter that is the text in the text node. Like createElement, the text node is a standalone node that needs to be added to the HTML document tree with appendChild

Example:

  var node = document.createTextNode("I'm a text node");
  document.body.appendChild(node);
Copy the code

The running results are as follows:

4.3 cloneNode

CloneNode returns a copy of the node that called the method

grammar

  var dupNode = node.cloneNode(deep);
Copy the code

(Optional) Whether to use deep cloning. If true, all descendant nodes of the node will be cloned. If false, only the node itself will be cloned.

Here are a few things to note: (1) Like createElement, cloneNode creates nodes that float outside the HTML document and are added to the tree by calling appendChild. (2) If the element has an ID, its copy contains that ID. The deep parameter received by the id (3) call is best passed in. If it is not passed in, different browsers may treat its default value differently

Note that if the replicated node is bound to an event, does the replica follow suit? (1) If the event is bound via addEventListener or, for example, onclick, the replica node will not bind the event. (2) If the event is bound inline, for example:

, in which case the replica node will also fire the event.

Example:

<body> <div id="parent"> I am the text of the parent element <br/> <span> I am the child element </span> </div> <button ID ="btnCopy"> Copy </button> </body> <script> var parent = document.getElementById("parent"); document.getElementById("btnCopy").onclick = function(){ var parent2 = parent.cloneNode(true); parent2.id = "parent2"; document.body.appendChild(parent2); } </script>Copy the code

The running results are as follows:

4.4 createDocumentFragment

DocumentFragments are DOM nodes. They are not part of the main DOM tree. The usual use case is to create a document fragment, attach elements to the document fragment, and then attach the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all of its child elements. Because the document fragment exists in memory, not in the DOM tree, inserting child elements into the document fragment does not cause page reflow (calculations of element position and geometry). Therefore, the use of document fragments is often used to optimize performance.

grammar

  let fragment = document.createDocumentFragment();
Copy the code

Example:

<body> <ul id="ul"></ul> </body> <script> (function() { var start = Date.now(); var str = '', li; var ul = document.getElementById('ul'); var fragment = document.createDocumentFragment(); for(var i=0; i<1000; i++) { li = document.createElement('li'); Li. TextContent = 'first '+(I +1)+' child '; fragment.appendChild(li); } ul.appendChild(fragment); }) (); </script>Copy the code

The running results are as follows:

4.5 Node creation API Summary

Node creation apis include createElement, createTextNode, cloneNode, and createDocumentFragment methods. Note the following: (1) The node they create is just an isolated node, AppendChild adds to the document (2) cloneNode takes care if the node being copied contains child nodes, event bindings, etc. (3) Use createDocumentFragment to solve performance problems when adding a large number of nodes

5 Page modification API

Earlier we mentioned node creation apis, which just create nodes without actually modifying them to the page content, but instead call ·appendChild· to add them to the document tree. I’m going to classify this type of modification as page content. Apis for modifying page content include: appendChild, insertBefore, removeChild, replaceChild.

5.1 appendChild

AppendChild we have used several times before to add the specified node to the end of the child element of the node calling the method.

grammar

  parent.appendChild(child);
Copy the code

The child node will be the last child of the parent node. The appendChild method is simple, but there is one more thing to note: If the node to be added is an existing node on the page, the node will be added to the specified location after execution, and the node will be removed from its original location, that is, there will not be two nodes on the page at the same time, which is equivalent to moving the node to another location. If a child is bound to an event, it remains bound to that event when moved.

Example:

<body> <div id="child"> Node to be added </div> <br/> <br/> <br/> <div id="parent"> Position to move </div> <input ID ="btnMove" Type ="button" value=" mobile node "/> </body> <script> document.getelementById ("btnMove"). Onclick = function(){var child = function() document.getElementById("child"); document.getElementById("parent").appendChild(child); } </script>Copy the code

Running results:

5.2 insertBefore

InsertBefore is used to add a node before a reference node

grammar

  parentNode.insertBefore(newNode,refNode);
Copy the code

ParentNode indicates the parentNode after the newNode is added. NewNode indicates the node to be added. RefNode indicates the reference node

Example:

<body> <div id="parent"> parent <div id="child"> </div> </div> <input type="button" id="insertNode" value=" insertNode" /> </body> <script> var parent = document.getElementById("parent"); var child = document.getElementById("child"); document.getElementById("insertNode").onclick = function(){ var newNode = document.createElement("div"); NewNode. TextContent = "newNode" parent. InsertBefore (newNode,child); } </script>Copy the code

Running results:

There are a few other things to note about the second reference node: (1) refNode is mandatory and an error will be reported if refNode is not passed. (2) insertBefore adds the node to the end of the child element if refNode is undefined or null

5.3 removeChild

Deletes the specified child node and returns

grammar

  var deletedChild = parent.removeChild(node);
Copy the code

DeletedChild is a reference to the deleted node, which is equal to node. The deleted node still exists in memory, ready for further action. Note: The program will report an error if the deleted node is not a child node. We can ensure deletion by:

if(node.parentNode){
    node.parentNode.removeChild(node);
}
Copy the code

Running results:

5.4 replaceChild

ReplaceChild is used to replace one node with another

grammar

  parent.replaceChild(newChild,oldChild);
Copy the code

NewChild is the replaced node, either a new node or a node on the page. If it is a node on the page, it will be moved to the new location. OldChild is the replaced node

Example:

<body>
  <div id="parent">The parent node<div id="child">Child elements</div>
  </div>
  <input type="button" id="insertNode" value="Replace node" />
</body>
<script>
  var parent = document.getElementById("parent");
  var child = document.getElementById("child");
  document.getElementById("insertNode").onclick = function(){
  	var newNode = document.createElement("div");
  	newNode.textContent = "New node"
  	parent.replaceChild(newNode,child)
  }
Copy the code

Running results:

5.5 Page modified API summary

Page modification apis are mainly composed of these four interfaces, with several features to note: (1) Whether a node is added or replaced, if the node is added or replaced and originally existed on the page, the node at its original location will be removed, that is to say, the same node cannot exist in multiple locations on the page. (2) Whether the event bound to the node itself will disappear, it will remain forever.

6 Node query API

6.1 document.getElementById

This interface is simple. It returns an Element based on its ID, with a value of type Element, or null if it doesn’t exist

grammar

  var element = document.getElementById(id);
Copy the code

There are a few caveats to using this interface: (1) the element’s Id is case sensitive and must be written to the Id of the element (2) there may be multiple Id the same element in the HTML document, it returns the first element (3) the only search elements from the document, if you create an element and specify the Id, but have not added to the document, this element is not be found

Example:

<body> <p id="para1">Some text here</p> <button onclick="changeColor('blue');" >blue</button> <button onclick="changeColor('red');" >red</button> </body> <script> function changeColor(newColor) { var elem = document.getElementById("para1"); elem.style.color = newColor; } </script>Copy the code

Running results:

6.2 document.getElementsByTagName

HTMLCollection returns an HTML collection containing all the elements of the given tag name. The entire file structure is searched, including the root node. Returns HTML collection is dynamic, which means it can automatically update themselves to maintain and synchronization of the DOM tree without invoking the document again. The getElementsByTagName ()

grammar

  var elements = document.getElementsByTagName(name);
Copy the code

(1) If the HTMLCollection is looped, it is best to cache its length, because each loop will calculate the length. Temporarily caching can improve efficiency. (2) If there is no specified tag, this interface does not return NULL. Instead, an empty HTMLCollection (3) name is a string that represents the name of the element. The special character “*” represents all elements.

Example:

<body> <div>div1</div> div2</div> <input type="button" value=" value "id="btnShowCount"/> <input type="button" Value = "new div id =" "btnAddDiv" / > < / body > < script > var divList = document. The getElementsByTagName (" div "); document.getElementById("btnAddDiv").onclick = function(){ var div = document.createElement("div"); div.textContent ="div" + (divList.length+1); document.body.appendChild(div); } document.getElementById("btnShowCount").onclick = function(){ alert(divList.length); } </script>Copy the code

There are two buttons in this code. One button displays the number of HTMLCollection elements and the other button adds a div tag to the document. The HTMLCollcetion element is an instant reference to the fact that the collection is changing at any time. That is, there are several divs in the document and it will change at any time. When we add a new div and visit HTMLCollection, the new div will be included.

Running results:

6.3 document.getElementsByName

GetElementsByName gets elements primarily through the specified name attribute, which returns a just-in-time NodeList object

grammar

  var elements = document.getElementsByName(name) 
Copy the code

The main points to note when using this interface are: In HTML elements, not all elements have a name attribute. For example, div does not have a name attribute, but it can be found if the name attribute of a div is forced. (3) In IE, If id is set to a certain value and getElementsByName is passed with the same value as ID, the element will be found, so it is best not to set the same value for ID and name

Example:

<script type="text/javascript">
  function getElements()
   {
   var x=document.getElementsByName("myInput");
   alert(x.length);
   }
</script>
<body>
  <input name="myInput" type="text" size="20" /><br />
  <input name="myInput" type="text" size="20" /><br />
  <input name="myInput" type="text" size="20" /><br />
  <br />
  <input type="button" onclick="getElements()" value="How many elements named 'myInput'?" />
</body>
Copy the code

Running results:

6.4 document.getElementsByClassName

This API returns a real-time HTMLCollection based on the element’s class

grammar

  var elements = document.getElementsByClassName(names); // or:
  var elements = rootElement.getElementsByClassName(names);
Copy the code
  • elementsIs a real-time collection that contains all the elements found
  • namesIs a string representing a list of class names to match; Class names are separated by Spaces
  • getElementsByClassNameCan be called on any element, not justdocument. The element that calls this method will be the root element for this lookup

This interface has the following points to note: (1) the return result is a real-time HTMLCollection that changes at any time depending on the structure of the document (2) The following browsers do not support it (3) If you want to get more than two classnames, you can pass in multiple classnames separated by Spaces, for example

  var elements = document.getElementsByClassName("test1 test2");
Copy the code

Example:

  • Get all theclassElement for ‘test’
  var elements = document.getElementsByClassName('test');
Copy the code
  • Get all theclassIncludes both ‘red’ and ‘test’ elements
  var elements = document.getElementsByClassName('red test');
Copy the code
  • inidIs the child node of the element ‘main’classElement for ‘test’
  var elements = document.getElementById('main').getElementsByClassName('test');
Copy the code
  • We can also use it with any HTMLCollectionArray.prototypeHTMLCollection is passed as an argument to the method. Here we’re going to find all of themclassFor ‘test’divChemical element:
  var testElements = document.getElementsByClassName('test');
  var testDivs = Array.prototype.filter.call(testElements, function(testElement){
    return testElement.nodeName === 'DIV';;
  });
Copy the code

6.5 document.querySelectoranddocument.querySelectorAll

The two apis are very similar in that they use CSS selectors to find elements. Note that the selectors conform to the rules of CSS selectors

  • 6.5.1 document. QuerySelector

Document. querySelector returns the first matched element, or null if there is no matched element

grammar

  var element = document.querySelector(selectors);
Copy the code

Note that since the first matching element is returned, the API uses depth-first search to retrieve the element.

Example:

<body> <div> <div> <span class="test"> Third level of span</span> </div> </div> <div class="test"> second level of div </div> <input Type ="button" id="btnGet" value=" test element "/> </body> <script> document.getElementById("btnGet").addEventListener("click",function(){ var element = document.querySelector(".test"); alert(element.textContent); }) </script>Copy the code

Both classes contain elements of “test”, one at the front of the document tree, but at level three, and one at the back of the document tree, but at level one, so when it gets an element by querySelector, it does a depth-first search to get the element at level three in front of the document tree. Running results:

  • Tactical fix packs for 6.5.2 document. QuerySelectorAll returns all of the matched elements, but also can match multiple selectors

grammar

  var elementList = document.querySelectorAll(selectors);
Copy the code
  • elementListIt’s a static oneNodeListObjects of type
  • selectorsIs a comma-concatenated string containing one or more CSS selectors
  • ifselectorsIf the argument contains CSS pseudo-elements, an empty one is returnedelementList

Example:

  var matches = document.querySelectorAll("div.note, div.alert");
Copy the code

Returns all div elements in a document whose class is “note” or “alert”

<body> <div class="test"> class= test </div> <div id="test"> ID = test </div> <input ID ="btnShow" type="button" Value =" display content "/> </body> <script> document.getelementById ("btnShow").addeventListener ("click",function(){var elements = document.querySelectorAll("#test,.test"); for(var i = 0,length = elements.length; i<length; i++){ alert(elements[i].textContent); } }) </script>Copy the code

This code selects two elements via querySelectorAll, using the ID selector and the class selector, and outputs their contents in turn. Note two things: (1) querySelectorAll is also a depth-first search, the order of the elements is independent of the order of the selectors. (2) It returns a non-real-time NodeList, meaning that the result does not change as the document tree changes. QuerySelector and querySelectorAll are not supported in browsers below Internet Explorer 8.

Running results:

7 Node relational API

The relationship between each node in an HTML document can be viewed as a family tree, including parent-child relationships, sibling relationships, and so on

7.1 Parent relational apis

7.1.1 parentNode

Each node has a parentNode attribute, which represents the element’s parentNode. The parent node of an Element may be Element, Document, or DocumentFragment

7.1.2 parentElement

Returns the parentNode of the Element, unlike parentNode in that its parent must be an Element, or null if it is not

7.2 Subrelationship APPI

7.2.1 childNodes

Returns a real-time NodeList that represents a list of the element’s children, which may contain text nodes, comment nodes, and so on

7.2.2 Children:

A real-time HTMLCollection with all the children elements. IE9 does not support the children property as read-only and the object type as HTMLCollection. You can use elementNodeReference. Children [1]. The nodeName to obtain a child element tag name

7.2.3 firstChild

The read-only property returns the first child of the node in the tree, or null if the node has no children

7.2.4 lastChild

Returns the last child of the current node. If the parent node is an element node, the child node is usually an element node, or a text node, or a comment node. If there are no child nodes, null is returned

7.2.5 hasChildNodes

Returns a Boolean value indicating whether the current node contains children.

7.3 Fraternal APIS

7.3.1 previousSibling

Browsers that return the previous sibling of the current node, if not a null Gecko kernel, insert a text node into the document where there is a space inside the tag in the source code. Therefore, using methods such as Node.firstChild and Node.previousSibling may refer to a blank text Node rather than the one the user expected

7.3.2 previousElementSibling

PreviousElementSibling returns the previous element node of the current element in the child element node of its parent, or null if the element is already the first element node, and the attribute is read-only. Notice The following browsers do not support Internet Explorer 9

7.3.3 nextSibling

Node.nextSibling is a read-only property that returns the Node immediately following its parent Node in the childNodes list. If the specified Node is the last Node, the browser that returns the null Gecko kernel inserts a text Node into the document where there is a whitespace inside the tag in the source code. Therefore, using methods such as Node.firstChild and Node.previousSibling may refer to a blank text Node rather than the one the user expected

Sections 7.3.4nextElementSibling

NextElementSibling returns the next element node of the current element in the child element node of its parent, or null if the element is already the last, and the attribute is read-only. Notice The following browsers do not support Internet Explorer 9

Element attribute API

8.1 setAttribute

Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; Otherwise a new attribute will be added with the specified name and value

grammar

  element.setAttribute(name, value);
Copy the code

Name is the feature name and value is the feature value. If the element does not contain the feature, it is created and assigned.

Example:

<body>
  <div id="div1">ABC</div>
</body>
<script>  
  let div1 = document.getElementById("div1"); 
  div1.setAttribute("align", "center");
</script>
Copy the code

Running results:

If the element itself contains the specified attribute named attribute, then the attribute can be assigned globally. For example, the following two codes are equivalent:

  element.setAttribute("id"."test");
  element.id = "test";
Copy the code

8.2 getAttribute

GetAttribute () returns a specified attribute value on the element. Returns null or “” (empty string) if the specified attribute does not exist

grammar

  let attribute = element.getAttribute(attributeName);  
Copy the code

Attribute is a string containing the value of the attributeName attribute. AttributeName is the attributeName of the attribute value that you want to retrieve

Example:

<body>
  <div id="div1">ABC</div>
</body>
<script>  
  let div1 = document.getElementById("div1");
  let align = div1.getAttribute("align");
  alert(align);
</script>  
Copy the code

Running results:

8.3 removeAttribute

RemoveAttribute () removes an attribute from the specified element

grammar

  element.removeAttribute(attrName)
Copy the code

AttrName is a string, the name of the attribute to be removed from the element

Example:

<body>
  <div id="div1" style="color:red" width="200px">ABC
   </div>
</body>
<script>  
  let div = document.getElementById("div1")
  div.removeAttribute("style");
</script>
Copy the code

Div had a style=”color:red” attribute before it was run, and this attribute was removed after it was run

Running results:

Element style API

9.1 window.getComputedStyle

The window.getComputedStyle () method gives the values of all CSS attributes of the element after the active stylesheet is applied, and parses any basic calculations that these values may contain assuming that an element is not set to height but is stretched by its content. To get its height, use getComputedStyle

grammar

  var style = window.getComputedStyle(element[, pseudoElt]);
Copy the code

Element is the element to get, and pseudoElt specifies a pseudo-element to match. The style returned is a CSSStyleDeclaration object. Style allows you to access the computed style of the element

9.2 getBoundingClientRect

GetBoundingClientRect is used to return the size of the element and its position relative to the browser’s visual window

grammar

  var clientRect = element.getBoundingClientRect();
Copy the code

ClientRect is a DOMRect object containing the left, top, right, and bottom distances relative to the visible window, whose values change when the scrolling position changes. Except in IE9 below, it also contains data such as the height and width of the element

9.3 Modify element styles directly

Example:

  elem.style.color = 'red';
  elem.style.setProperty('font-size'.'16px');
  elem.style.removeProperty('color');
Copy the code

9.4 Dynamically Adding Style Rules

Example:

  var style = document.createElement('style');
  style.innerHTML = 'body{color:red} #top:hover{background-color: red; color: white; } ';
  document.head.appendChild(style);) ;Copy the code

10 summary

There are so many apis in JavaScript that it is very helpful to memorize these apis and use them proficiently