What are the operation methods of DOM nodes
This article introduces the relevant knowledge of "what are the operating methods of DOM nodes". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
DOM can not only find nodes, but also create nodes, copy nodes, insert nodes, delete nodes, and replace nodes.
Node operation method
Method description
Write () inserts any string into the document
CreateElement () creates an element node
AppendChild () appends the new node to the end of the list of child nodes
CreateTextNode () creates a file node
InsertBefore () inserts the new node in front
RepalceChild () replaces the old node with the new node
CloneNode () replication node
RemoveChild () removes a node
1.write () method
The write () method can insert any string into the document.
[xss_clean] ('
This is a paragraph!
')'; / / output any string
2.createElement () method
The createElement () method creates an element node.
Document.createElement ('p'); / / create an element node
3.appendChild () method
The appendChild () method adds a new node to the end of the list of child nodes of a node.
Var box = document.getElementById ('box'); / / get an element node
Var p = document.createElement ('p'); / / create a new element node
Box.appendChild (p); / / put the new element node
Add the end of the child node
4.createTextNode () method
The createTextNode () method creates a text node.
Var text = document.createTextNode ('paragraph'); / / create a text node
P.appendChild (text); / / add a text node to the end of the child node
5.insertBefore () method
The insertBefore () method creates the node in front of the specified node.
Box [XSS _ clean] .insertBefore (p, box); / / create a node before
The PS:insertBefore () method creates a node in front of the current element, but does not provide a node after the current element. Then, we can create an insertAfter () function with what we already know.
Function insertAfter (newElement, targetElement) {
/ / get the parent node
Var parent = targetElement [XSS _ clean]
/ / if the last child node is the current element, you can add it directly
If (parent.lastChild = targetElement) {
Parent.appendChild (newElement)
} else {
/ / otherwise, add before the next node of the current node
Parent.insertBefore (newElement, targetElement.nextSibling)
}
}
Var input = null
If (BrowserDetect.browser = = 'Internet Explorer' & & BrowserDetect.version