This document introduces how to use JavaScript DOM to modify document tree and how to use JavaScript DOM to create and clone elements, let's start with the most basic elements of the HTML page:
- <!--
-
- <title>DOM Examlie</title>
-
- <body>
- <p>Hello World !</p>
- </body>
-
When accessing the
- Var ohtml#document.doc umentElement; // you can directly access the
- Alert ("node name:" + oHtml. nodeName); // node name
- Alert ("Node Type:" + oHtml. nodeType); // The node type is 1
Obtain the
- Var oHead = oHtml. firstChild; // HEAD node
- Var oBody = oHtml. lastChild; // BODY Node
You can also use the childNodes attribute to obtain the
- Var oHead = oHtml. childNodes. item (0); // HEAD node
- // Var oHead = oHtml. childNodes [0]; // abbreviation, the same result is the HEAD node.
- Var oBody = oHtml. childNodes. item (1); // BODY Node
- // Var oBody = oHtml. childNodes. item (1); // abbreviation. The same result is the BODY node.
Note: The square brackets mark is actually a simple implementation of NodeList in javascript. In fact, the method for obtaining subnodes from the childNodes list is to use the item () method: document. body, a proprietary attribute in the html dom, which is often used to directly access elements:
- var oBody=document.body;
Since we all know how to obtain the above node objects, we use the three variables oHtml, oHead, and oBody to determine the relationship between them:
- Alert (oHead. parentNode = oHtml); // The parent node of the HEAD node is the BODY node, and true is returned.
- Alert (oBody. parentNode = oHtml); // The parent node of the BODY node is the BODY node, and true is returned.
- Alert (oBody. previussibling = oHead); // The Last sibling node of the BODY node is the HEAD node, and true is returned.
- Alert (oHead. nextSibling = oBody); // The next sibling node of the HEAD node is the BODY node, and true is returned.
- Alert (oHead. ownerDocument = document); // returns the root element (Document) of a node. returns true if the HEAD node points to this document.
Through the above learning, we have learned the most basic way to traverse a node and how to find the brother node and its child node of a node.