Learning to operate DOM

Learning to operate DOM

DOM (Document Object Model) is a set of technical specifications formulated by W3C. It is a Web standard used to describe how JavaScript scripts interact with HTML or XML documents.

DOM stipulates that the whole document is a document node, each element is an element node, the text contained in the element is a text node, the attribute of the element is an attribute node, and the annotation belongs to the annotation node, etc.

Each node has a nodeType attribute, which indicates the type of the node. The return value of the nodeType attribute can be used to determine the type of a node. The common values are as follows:
The nodeType value of Element is 1, the nodeType value of attribute Attr is 2, the nodeType value of text is 3, and the nodeType value of document is 9
You can read the name and value of a node by using the nodeName and nodeValue properties of the node, which depend entirely on the type of node.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<body>
<script>
    var node = document.getElementsByTagName("body")[0] ;
    if(node.nodeType == 1){ //First check the node to see if it is an element. If yes, read the value in nodeName
        var value = node.nodeName ;
        document.write(value) ;
    }
    if(node.nodeType == 2){ //Check whether the node is an attribute
        var value1 = node.nodeName() ;
        document.write(value1) ;
    }
    if(node.nodeType == 3){ //Check whether the node is text
        var value2 = node.nodeName() ;
        document.write(value2) ;
    }
    if(node.nodeType == 8){ //Check whether the node is a comment
        var value3 = node.nodeName() ;
        document.write(value3) ;
    }
    if(node.nodeType == 9){ //Check whether the node is a document
        var value4 = node.nodeName() ;
        document.write(value4) ;
    }

</script>
</body>
</html>

DOM defines the following attributes for nodes to facilitate JS to traverse each Node of the document.
ownerDocument: returns the root element of the current node
parentNode: returns the parent node of the current node
childNodes: returns the node list of all child nodes of the current node
firstChild: returns the first child node of the current node
lastChild: returns the last node of the current node
nextSibling: returns the sibling adjacent node after the current node
previousSibling: returns the previous adjacent sibling node of the current node

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<body>
<script>
    var node = document.getElementsByTagName("body")[0] ;
    if(node.nodeType == 1){ //First check the node to see if it is an element. If yes, read the value in nodeName
        var value = node.nodeName ;
        document.write(value + "<br>") ;
    }
    document.write(node.ownerDocument + "<br>") ; //Returns the root element object of the current node
    document.write(node.parentNode +  "<br>") ; //Returns the parent node of the current node
    document.write(node.childNodes +  "<br>") ; //Returns the child node of the current node
    document.write(node.firstChild +  "<br>") ; //Returns the first child node of the current node
    document.write(node.lastChild +  "<br>") ; //Returns the last child node of the current node
    document.write(node.nextSibling +  "<br>") ;//Returns the sibling node next to the current node
    document.write(node.previousSibling +  "<br>") ; //Returns the adjacent node before the current node
</script>
</body>
</html>

Node type defines many prototype methods for all nodes to facilitate the operation of nodes. The methods unanimously supported by all browsers are as follows:
appendChild(): add a child node to the end of the current node
cloneNode(): copy nodes
hasChildNodes(): judge whether the current node has child nodes
insertBefore(): inserts a new node before the specified node
normalize(): merge adjacent Test nodes to help delete empty tests
node
removeChild(): deletes the child nodes of the current node
replaceChild(): replace a child node with a new node

There are two ways to access document child nodes:
1 - use the documentElement attribute, which always points to the HTML element of the HTML page.
2 - access document elements using the childNodes list.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<body>
<script>
    var html1 = document.documentElement ;
    var html2 = document.childNodes[0] ;
    var html3 = document.firstChild ;
    document.write(html1 + "<br>") ;
    document.write(html2 + "<br>") ;
    document.write(html3 + "<br>") ;
    var body = document.body ;
    document.write(body + "<br>") ;
    var doctype = document.doctype ;
    document.write(doctype + "<br>") ;
</script>
</body>
</html>

Access document information
The instance object document of HTMLDocument contains many attributes to access document information, mainly as follows:
Title: returns the information contained in the title tag.
lastModified: returns the date and time when the document was last modified.
URL: returns the full URL of the current document, that is, the address information displayed in the address bar
Domain: returns the domain name of the current document
Refer: return to the URL of the linked page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>A boy who dreams as a horse will eventually have the answer to reach the stars in the universe!!!</title>
<body>
<script>
    document.write(document.title + "<br>") ; //Returns the text information contained in the title tag
    document.write(document.lastModified + "<br>") ; //The time and date when the document was last modified
    document.write(document.URL + "<br>") ; //Returns the full URL of the current document
    document.write(document.domain + "<br>") ; //Returns the domain name of the current document
    document.write(document.referrer + "<br>") ; //Returns the URL of the page linked to the current page
</script>
</body>
</html>

Access document elements. Document contains multiple methods to access document elements. The brief description is as follows:
getElementById(): returns the element with the specified id attribute value
getElementsByTagName(): returns the element node of the specified tag name
getElementsByName(): returns all element nodes with the specified name

The getElementById() method can be used to accurately obtain the elements specified in the document. Gets the id attribute value in the corresponding document. If the specified element does not exist in the document, null is returned. This method is only applicable to document objects.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>A boy who dreams as a horse will eventually have the answer to reach the stars in the universe!!!</title>
<body>
<div id = "box">Box</div>
<script>
    var box = document.getElementById("box") ; //Gets a reference to the specified box
    var info = "nodeName = " + box.nodeName ; //Gets the name of the node
    info +=  "\rnodeType = " + box.nodeType ; //Gets the type of the node
    info += "\rparentNode = " + box.parentNode.nodeName ; //Gets the name of the parent node of the node
    info += "\rchildNode = " + box.childNodes[0].nodeName ; //Gets the name of the child node of the node
    alert(info) ; //Display prompt information
</script>
</body>
</html>

getElementsByTagName() returns an HTMLCollection object, which is similar to the nodeList object. You can use square bracket syntax or item() method to access the elements in the HTMLCollection object and obtain the number of elements in the object through the length attribute.

To access a document collection, document defines some collection properties. These collections are HTMLCollection objects, which provide shortcuts to access document objects.

The getElementsByTagName() method can get all the elements of the specified tag name.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>A boy who dreams as a horse will eventually have the answer to reach the stars in the universe!!!</title>
<body>
<div id = "p" >good morning</div>
<script>
    var p = document.getElementsByTagName("p") ; //Gets a reference to the p tag
    for(var i=0; i<p.length; i++){
        p[i].setAttribute("class", "red") ; //Define the red style for each p element
        document.write(p[i] + "<br>") ;
    }
</script>
</body>
</html>

The createElement() method can create a new element according to the specified label name and return a reference to the new element.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>A boy who dreams as a horse will eventually have the answer to reach the stars in the universe!!!</title>
<body>
<div id = "p" >good morning</div>
<script>
    var p = document.createElement("p") ; //Create paragraph element
    var info = "nodeName : " + p.nodeName ; //Get element name
    info += " nodeType : " + p.nodeType ; //Get element type
    alert(info) ;
</script>
</body>
</html>

Copy the element. The cloneNode() method can create a copy of the node, that is, copy the node element.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>A boy who dreams as a horse will eventually have the answer to reach the stars in the universe!!!</title>
<body>
<div id = "p" >good morning</div>
<script>
    var p = document.createElement("p") ; //Create paragraph element
    var info = "nodeName : " + p.nodeName ; //Get element name
    var node = p.cloneNode(false) ; //Replication node
    alert(info) ;
    alert(node.nodeName) ;
</script>
</body>
</html>

There are two main methods to insert a node into a document.
1-appendChild() method
This method is used to add a new child node to the end of the child node list of the current node.
2-insertBefore() method
This method can insert a new node before the existing child node.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>A boy who dreams as a horse will eventually have the answer to reach the stars in the universe!!!</title>
<body>
<div id = "box" >Box</div>
<script>
    var p = document.createElement("p") ;
    var txt = document.createTextNode("Box model") ;
    var r = p.appendChild(txt) ; //Add a text node after a paragraph node
    var res = document.getElementById("box").appendChild(p) ; //Get the element of box and add the p node after it
    document.write(r.nodeName + "<br>") ;
    document.write(res.nodeName) ;
</script>
</body>
</html>

If a parameter node already exists in the document tree, delete it from the document tree and re insert it into a new location. If a DocumentFragment node is added, it will not be inserted directly, but its child nodes will be inserted to the end of the previous node in order.

Insert before (new child, old child): insert a new node before the old node

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>A boy who dreams as a horse will eventually have the answer to reach the stars in the universe!!!</title>
<body>
<div id = "box" >Box</div>
<script>
    var ok = document.getElementById("ok") ; //Gets a reference to the button element
    var red = document.getElementById("red") ; //Get the reference of the red box
    var blue = document.getElementById("blue") ; //Get the reference of the blue box
    var h1 = document.getElementsByTagName("h1").[0] ; //Gets a reference to the title element
    red.insertBefore(blue, h1) ; //Move the blue box into the red box and in front of the title
</script>
</body>
</html>

Keywords: Javascript node.js html5

Added by sasa on Sat, 09 Oct 2021 16:18:37 +0300