In the previous article, we talked about using dom to create, copy, and insert nodes. Today we will talk about deleting nodes, replacing nodes, and searching nodes. In the previous article, we talked about using dom to create, copy, and insert nodes. Today we will talk about deleting nodes, replacing nodes, and searching nodes.
Start with the method:
1. delete a node. RemoveChild ():
A
B
C
Script
Var msg = document. getElementById ("cssrain ");
Var B = document. getElementById ("B ");
Msg. removeChild (B );
Script
If you do not know the parent node of the node to be deleted? You can use the parentNode attribute.
For example:
A
B
C
Script
Var B = document. getElementById ("B ");
Var c = B. parentNode;
C. removeChild (B );
Script
2. Replace the node. RepalceChild ()
Element. repalceChild (newNode, oldNode); // The new node is a guest and must be served first .. The oldNode must be a subnode of the Element.
Example:
A
B
C
Script
Var cssrain = document. getElementById ("cssrain ");
Var msg = document. getElementById ("B ");
Var para = document. createElement ("p ");
Cssrain. replaceChild (para, msg );
Script
3. Search for nodes
Compared with the above method, it is relatively simple to search for nodes.
Because many people have used it. (Remember that the first sentence I know about js is getElementById ();)
GetElementById ();
Returns an object with attributes such as nodeName, nodeType, parentNode, and ChildNodes.
GetElementsByTagName () is used to find all elements of a tag name.
Returns a set of objects that can be retrieved cyclically. Objects have attributes such as nodeName, nodeType, parentNode, and ChildNodes.
Example:
Var ps = document. getElementsByTagName ("p ");
For (var I = 0; I <ps. length; I ++ ){
Ps [I]. setAttribute ("title", "hello ");
// You can also use: ps. item (I). setAttribute ("title", "hello ");
}
4. Set/obtain attribute nodes.
SetAttribute (); // set
Example:
Var a = document. createElement ("p ");
A. setAttribute ("title", "my demo ");
Whether the title attribute exists or not, the subsequent value is my demo.
GetAttribute (); // get
Example:
Var a = document. getElementById ("cssrain ");
Var B = a. getAttribute ("title ");
If the property does not exist, null is returned. Note that ie and ff return different values.
Aaaa
Bbbb