Document Object Model (DOM) is a programming interface for HTML and XML documents. Generally speaking, a web page is structured by HTML, style defined by CSS, and interaction with the page completed by JS. DOM is the web page and JS connection channel, it is THE INTERFACE of JS web page operation, the Web page and programming language connected. In plain English, it is a set of apis for markup languages. When a web page is loaded, the browser creates a document object model of the page, which can be dynamically changed through the DOM.

The browser parses the HTML document into a series of nodes based on the DOM model, which form a tree structure. The smallest unit of DOM is called a node. The DOM tree consists of these nodes. Nodes are divided into many types, each of which has its own characteristics and methods for different information and tags in the document. Through the DOM node hierarchy diagram parsed by the HTML code below, we can see the relationship between nodes more clearly. The document node represents the root node of the document, whose only child element is the < HTML > document element (there can only be one document element per document). The entire document is a document node, each HTML element is an element node, the text within an HTML element is a text node, each HTML attribute is an attribute node, and a comment is a comment node. There are 12 node types in the DOM. The important types are described below.

The Node type

1, the nodeType

In JavaScript, all Node types inherit from Node types, so all types share the same basic properties and methods. Generally, nodes have nodeType, nodeValue, and nodeName attributes. The nodetypes of some common nodes are as follows:

node NodeType value
Node.ELEMENT_NODE 1
Node.ATTRIBUTE_NODE 2
Node.TEXT_NODE 3
Node.COMMENT_NODE 8
Node.DOCUMENT_NODE 9

If you want to determine the type of a node, you can do so by comparing it with these constants:

if(someNode.nodeType == 1){
    alert('node is an element')}Copy the code

The nodeValue and nodeName properties hold information about the node, depending on the node type. For elements, nodeName is always equal to the element’s label name, and nodeValue is always null.

<body>
    <div id="box">box</div>
    <script>
        var box = document.getElementById('box');
        console.log(box.nodeType); / / 1
        console.log(box.nodeName); //DIV
        console.log(box.nodeValue); //null
        // to access the tagName of an element, you can use the nodeName and tagName attributes, which return the same value.
        console.log(box.nodeName == box.tagName); //true
    </script>
</body>
Copy the code

2. Node relationship

All nodes in a document have relationships with other nodes that can be described as family relationships. We can describe these relationships in terms of father, son, and sibling. In a tree of nodes, the top node is called root, and each node has a parent (except root). A node can have any number of children. Siblings are nodes that have the same parent.

Each node has a childNodes property that contains an instance of NodeList. It holds the first-level child nodes of this node. The NodeList instance, which stores ordered nodes that can be accessed by location, is a real-time query of the DOM structure, and its value can be accessed through the Length attribute or brackets.

Each node has a parentNode attribute that points to its parent element in the DOM tree. All nodes in childNodes have the same parent element. They have the same praentNode. Each node in the childNodes list is a sibling of another node in the same list and can be searched using previousSibling or nextSibling. If there is only one node in chidNodes, its previousSibling and nextSibling are both null.

FirstChild and lastChild point to the first and lastChild nodes in childNodes, respectively. If there’s only one child node then these two point to the same node.

Therefore, we can obtain nodes through the following methods:

  • Document.documentelement Gets the HTML element
  • Document. head gets the header element
  • Document. body gets the body element
  • Node. parentNode obtains the parentNode
  • Element. childNodes Retrieves all children of a given node, including text nodes and comment nodes
  • Element. children gets all the children of an existing element, returning only the element node
  • Node. The firstChild/node. LastChild get the first child/the last child node
  • Node. FirstElementChild/node. LastElementChild access to the first element node/the last element
  • Node.nextsibling/node.previoussibling gets the next/previousSibling of a known node
  • Node. NextElementSibling/node. PreviousElementSibling similar nextSibling and previousSibling, but only represent brothers element.

3. Manipulate nodes

3.1 Adding a Node

The most common method of manipulating nodes in the DOM is parentNode.appendChild() or parentNode.insertbefore (). Create a new Element node using the createElement() method of the Document object and then insert it into the Document using appendChild() or insertBefore(). Here we need to note:

  • When the document.createelement (tagName) method is used, it takes the tagName of the element;
  • The appendChild(newNode) method is called on the parent of the newNode and is used to add the node at the end of the childrenNodes list.
  • If you want to place a node at a specific location in childrenNodes instead of at the end, use the insertBefore() method, which takes two arguments, the node to be inserted and the reference node, and the node to be inserted will be inserted before the reference node and returned. InsertBefore () has the same effect as appendChild() if the reference node is null.
  • Calls appendChild() or insertBefore() reinsert a node that already exists in the document, and that node is automatically removed from its current location and reinserted in the new location.
    <ul class="list" id="list">
        <li>1</li>
        <li>2</li>
    </ul>
    <script>
        var ul = document.getElementById('list');
        var liNode = document.createElement('li');
        liNode.style.background = 'pink';
        ul.insertBefore(liNode, null);// Insert the node
        // ul.appendChild(liNode);
        var num = -1;
        var max = ul.children.length;
        function fn() {
            num++;
            ul.insertBefore(liNode, ul.getElementsByTagName('li')[num]);
            if (num == max) {
                num = -1;
            }
            if (num == 0) {
                num = 1;
            }
            setTimeout(fn, 1000);
        }
        setTimeout(fn, 1000);
    </script>
Copy the code

3.2 Deleting a Node

To remove a node, the parentNode.removechild (childNode) method is used to remove the specified node from the parent. The argument is the node to be removed, and the node to be removed is returned. Of course, we can also use remove() method directly to remove the node, this method does not call the parent node, directly on the current node remove() method returns no value.

    <button id="btn"</button><ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <script>
        var ul = document.querySelector('ul');
        var btn = document.getElementById('btn');
        function fn() {
            // Get the number of Li
            var len = ul.getElementsByTagName('li').length;
            // If the length is not 0
            if (len) {
                // Remove the last child element
                ul.removeChild(ul.getElementsByTagName('li')[len - 1]);
                // Call the timer again
                setTimeout(fn, 1000);
            }
        }
        btn.onclick = function () {
            setTimeout(fn, 1000)}</script>
Copy the code

3.3 Cloning a Replication Node

The parentNode.clonenode (deep) method can also be used to clone a specified node. Clone the element and its descendants when the argument is true. Clone only the current node when the argument is false. Default is false. The cloneNode() method returns the same node as the one on which it was called. Although the copied node is part of the document, it is an orphan node and needs to be added to the document. Note that this method can only clone the HTML and CSS on the node, the javascript attributes contained in the node will not be cloned, if the cloned element itself has the ID attribute, then the cloned element will also have the ID attribute, the two are the same, this does not meet the standard, we need to manually modify the ID attribute.

    <ul id="list">
        <li>1</li>
    </ul>
    <script>
        var ul = document.getElementById('list');
        ul.index = 0;
        var deepList = ul.cloneNode(true);
        // The child node was successfully copied
        console.log(deepList.children.length);/ / 1
        // The properties are not copied
        console.log(deepList.index);//undefined
        var shallowList = ul.cloneNode();
        // Shallow replication does not copy child nodes
        console.log(shallowList.children.length);/ / 0
    </script>
Copy the code

3.4 Replacing a Node

The parentNode.replacechild (newNode,oldNode) method takes two arguments, the newNode to be inserted and the oldNode to be replaced. NewNode can be an existing node in the document or a newly created node. The node to be replaced is returned and completely removed from the document tree, and the node to be inserted is replaced.

    <input type="button" id="btn" value="Replacement">
    <ul>
        <li>a</li>
        <li>b</li>
        <li>c</li>
    </ul>
    <script>
        window.onload = function () {
            var btn = document.getElementById('btn');
            var lis = document.querySelectorAll('li');
            btn.onclick = function () {
                ul.replaceChild(lis[2], lis[0]); }}</script>
Copy the code

The Document type

1. Basic knowledge

The Document type is the type of Document node in JS, and the Document object in the browser is an instance of HTMLDocument, which represents the entire HTML page. Document is an attribute of the Window object and is therefore a global object. Although the Document type can also represent XML documents, the Document object is most commonly obtained through an instance of HTMLDocument. The Document object can be used to get information about a page and manipulate its appearance and underlying structure. A Document node has the following characteristics:

  • NodeType 9
  • NodeName for ‘# document’
  • NodeValue value is null
  • ParentNode value is null
  • Document.documentelement points to an HTML element
  • Document. body points to the body element

Document can also write to the web page output stream. There are four methods: Write (), writeIn(), open(), and close(). You can also use the innerHTML property to set or read the HTML content of an element, or use the innerText property to set or read the plain text content of an element.

    <input type="button" id='btn' value="Closed""> Copy the code

2. Locate elements

describe methods The return value
Get the element through the ID attribute document.getElementById(id) chooseaElement based on a unique ID
Get the element through the name attribute document.getElementsByName(name) You get a NodeListAn array of classobject
Gets the element by tag name document.getElementsByTagName(tagName) Get an HTMLCollectionAn array of classobject
Get the element through the class attribute document.getElementsByClassName(className) To get aAn array of classobject
Get elements through CSS selectors querySelector(selector)/querySelectorAll(selector) getaElement/get oneAn array of classobject

Element type

1. Basic knowledge

In addition to the Document type, the Element type is the most commonly used type in Web development. Nodes of Element type have the following characteristics:

  • NodeType 1
  • The nodeName value is the tag name of the element
  • NodeValue value is null
  • The value of parentNode is Document or Element

We can get the tagName of an element by using either the nodeName or tagName attribute, which returns the same value.

// In HTML, element tag names always start with uppercase, but in XML, the case is the same as in the signature and code
if(element.tagName.toLowerCase() == 'div') {// do something 
}
Copy the code

2, methods,

Each element has zero or more attributes, often used to attach more information to the element or its contents. There are three DOM methods related to attributes: getAttribute(), setAttribute() and removeAttribute(). These three methods are mainly used to manipulate attributes, including those defined on the HTMLElement type. Typically we create a property on a node with document.createElement() and then perform a series of operations on the property.

  • document.createAttribute()
    <div></div>
    <script>
        var attr = document.createAttribute('id');
        attr.value = "box";
        document.getElementsByTagName('div') [0].setAttributeNode(attr);
    </script>
Copy the code
  • Element. getAttribute(attributename) retrieves the value of a node attribute by the attributename, or if the parameter is SRC or href, the result is the quoted value (relative address). It doesn’t get js custom attributes, but it can get HTML tag custom attributes.

  • Element. The setAttribute (attributeName, attributeValue) set properties. The parameters must be present at the same time. If the attribute already exists, setAttribute() replaces the original value with the specified value, and if the attribute does not exist, setAttribute() creates the attribute with the specified value. You can set custom properties or properties in the system.

  • Element. removeAttribute Removes an attribute.

You can also style HTML elements using the DOM.

  • Label object.style.css Property name = value
  • Set the class attribute of an element to change multiple CSS attributes at the same time
    <div id="box" n="myName" class="color" data-v="myName">
        <img id="pic" src="./img/1.jpg" />
    </div>
    <script>
        var box = document.getElementById('box');
        var pic = document.getElementById('pic');
        console.log(pic.getAttribute('src')) //./img/1.jpg
        // It does not get the js custom attributes
        box.index = 1;
        console.log(box.getAttribute('index')); //null
        // It can take custom attributes from HTML tags
        console.log(box.getAttribute('n')); //myName
        console.log(box.dataset.v);//myName h5 added, note that the dat- start
        box.setAttribute('id'.'box2');
        box.removeAttribute('style'); 
    </script>
</body>
Copy the code

The Text type

1. Basic knowledge

A Text node is represented by a Text type, which contains literal plain Text and may contain escaped HTML characters but no HTML code. A Text node has the following characteristics:

  • NodeType is 3
  • NodeName value of ‘# text’
  • The nodeValue value returns the text contained in the node
  • The parentNode value is an Element object
  • Child nodes are not supported

2, methods,

Text content seen on a web page belongs to this node. Text nodes are represented by type Text and contain plain Text content, but Text nodes are object types. The Text contained in the Text node can be accessed through either the nodeValue property or the data property. The two properties contain the same value, and changes to the nodeValue or data property are also reflected in the other property. The text node exposes the following methods for manipulating text:

  • Document.createtextnode () creates a new text node
  • AppendData (text) Adds text text to the end of the node
  • DeleteData (offset,count) Deletes count characters from position offset
  • InsertData (offset,text) Inserts text at position offset
  • ReplaceData (offset,count,text) Replaces the text from position offset to offset+count with text
  • SplitText (offset), where offset splits the current text into two text nodes
  • SubstringData (offset,count), extracts the text from position offset to offset+count

In addition to these methods, you can also get the number of characters contained in the text node via the length attribute, which is equal to nodevalue.length and data.length.

By default, each element containing text content can have at most one text node. However, you can also have an element that contains multiple text child nodes.

  <script>
        let element = document.createElement('div');
        element.className = 'box';
        let textNode = document.createTextNode('hello world! ');
        element.appendChild(textNode);
        let anotherTextNode = document.createTextNode('Hello, world! ')
        element.appendChild(anotherTextNode);
        document.body.appendChild(element);
        After inserting a text node as a sibling of another text node, there is no space between the text of the two text nodes
      var text = element.firstChild;
      console.log(text.nodeValue == text.data);//true
      console.log(text.length == text.data.length ) //true
    </script>
Copy the code

Attr type

Element data is represented in the DOM by the Attr type, and the Attr type constructors and stereotypes are directly accessible in all browsers. Technically, attributes are nodes that exist within the attributes attribute of an element. Attr nodes have the following characteristics:

  • NodeType is 2
  • The nodeName value is the attribute name
  • NodeValue Indicates the attribute value
  • ParentNode value is null
  • Child nodes are not supported in HTML

Attribute nodes, though nodes, are not considered part of the DOM document tree. Attr nodes are rarely referred to directly, and attributes are usually manipulated using getAttribute(),removeAttribute(), and setAttribute() methods.

The Comment type

Comments in the DOM are represented by the Comment type. Nodes of Comment type have the following characteristics:

  • NodeType is 8
  • NodeName value of ‘# comment’
  • NodeValue Indicates the content of the comment
  • The parentNode value is Document or Element
  • Child nodes are not supported

DocumentType type

The DocumentType node DocumentType contains DocumentType (doctype) information. With the following characteristics:

  • NodeType is 10
  • The nodeName value is the name of the document type
  • NodeValue is null
  • ParentNode is the Document,
  • Child nodes are not supported

DocumentFragment type

Of all the node types, the DocumentFragment type is the only one that does not have a corresponding representation in the tag. DOM defines document fragments as “lightweight” documents. Being able to include and manipulate nodes without the additional cost of full documentation. The DocumentFragment node has the following characteristics:

  • NodeType is 11;
  • NodeName = “#document-fragment”;
  • NodeValue is null.
  • The parentNode value is null.
  • You cannot add document fragments directly to a document

DOM programming

Each node in HTML is an instance object of DOM, and each kind of object has its own attributes and methods. The most commonly used are the table table and various form elements form object

1, forms,

Form element objects include input field objects, Slect objects, option objects, other form elements, etc.

1.1 the form object

Properties:

The name of the describe
elements[] Get all the elements in the form
action Url to submit to the server
id The form of id
name The name of the
length The number of elements in the form
target The jump target for the current form
Methods:
  • Reset () resets all input elements of the form to their default values
  • Submit () submits the page based on the form’s action and method
    <form action="" id='myForm'>
        <input type="text">
        <button id='btn' onclick="formSubmit()">submit</button>
    </form>
    <script>
        function formSubmit() {
            document.getElementById('myForm').submit();
        }
    </script>
Copy the code

1.2 the button object

attribute

The name of the describe
disabled Sets or gets the property whether the button is invalid
form Returns the form where the button resides
id Sets or gets the ID of the button
name Sets or gets the name of the button
value Sets or gets the value displayed for the button
methods
  • Click () The event triggered by a click that simulates a mouse click on the button
  • Focus () Sets the focus of the button

1.3 CheckBox or Radio Object

  • attribute
    • Checked sets or returns whether it should be checked
  • methods
    • Blur (): Move focus away from the checkbox
    • Click (): Simulates a mouse click in a checkbox
    • Focus (): Assigns focus to the checkbox

1.4 the select objects

  • attribute
    • Options [] returns an array containing all the options in the drop-down list
    • SelectedIndex Sets or returns the index of the selected item in the drop-down list
    • Length Number of options in the drop-down box
    • Size Number of visible rows in the drop-down box
  • methods
    • Add () adds an option
    • Remove () removes an option

1.5 option object

attribute

  • Index Returns the index position of an option in the drop-down list
  • Selected Sets or checks whether the option is selected or not
  • Text Sets or views the text value of the option
  • Value Sets or views the value represented by the option

2, form

Tables are one of the most complex structures in HTML. Creating a table element through DOM programming usually involves a lot of tags. That includes rows, cells, and so on. The HTML DOM adds attributes and methods to the <table>,< tBody >, and <tr> elements.

attribute methods
The <table> element adds the following attributes and methods (commonly used) :
tBodies HTMLCollection containing < tBody > elements
rows Contains an HTMLCollection that represents all lines
insertRow(pos) Inserts a row at a given position in the row collection
deleteRow(pos) Deletes the row at the given position
The < tBody > element adds the following attributes and methods (commonly used) :
rows HTMLCollection containing all the lines in the < tBody > element
deleteRow(pos) Deletes the row at the given position
insertRow(pos) Returns a reference to a row inserted at a given position in the row collection
The <tr> element adds the following attributes and methods (common) :
cells contains
rowIndex Returns the position of the row in the table (starting at 0)
insertCell(pos) Inserts a table element at a given position in the table element set and returns a reference to the table element
deleteCell(pos) Deletes the table element at the given location
The tablecell object represents an HTML tablecell:
celllndex The position of a cell in a row cell collection
innerHTML Sets or returns the HTML between the start tag and end tag of a cell

These properties and methods greatly reduce the amount of code required to create the table.

    <table id="table"></table>
    <script>
        var ary = ['id'.'name'.'age'.'sex']
        var table = document.getElementById('table');
        var tr = table.insertRow(0);
        for (var i = 0; i < ary.length; i++) {
            tr.insertCell().innerHTML = ary[i];
        }
        console.log('The second cell in the first row is' + table.rows[0].cells[1].innerHTML)// The second cell in the first row contains name
    </script>   
Copy the code