This article mainly introduces JavaScript to automatically generate webpage elements. It lists three methods for adding, deleting, modifying, and cloning buttons, text, and other elements, if you are interested, refer to the method for creating elements:
- 1. Use createTextNode () to create a Text object
- 2. Create a tag object using createElement ()
- 3. directly use an attribute in the container tag: innerHTML ----- essentially modifying the "html code" in the tag container is not an operation of the object tree we think.
Detailed code:
This is the p module --
You must study well so that you can get a good return.
Good job, come on (^ ω ^)
You know regions, lab Areas
Method 1: Create a text document
Function addNode1 () {// 1 use createTextNode () to create a text object var text = document. createTextNode ("this is modified, the document created"); // 2 get the p object var node1 = document. getElementById ("p_id1"); // Add the child node1.appendChild (text) as the p object );}
Method 2: Create a tag object using createElement ()
Function addNode2 () {// 1. Use createElement () to create a label object var nn = document. createElement ("input"); nn. type = "button" nn. value = "created button"; nn.tar get = "_ blank"; // 2, get the p object var node2 = document. getElementById ("p_id2"); // Add the child node2.appendChild (nn) as the p object );}
Method 3: directly use an attribute in the container tag: innerHTML ----- essentially modifying the "html code" in the tag container, which is not an operation of the object tree we think.
Function addNode3 () {var mm = document. getElementById ("p_id3"); mm. innerHTML ="";}
You can use removeNode or removeChild to delete child nodes from an element. The second method is usually used.
Function removenode () {var node = document. getElementById ("p_id4"); // alert (node. nodeName); // DIV // suicide node. removeNode (true); // removeNode deletes an object from the document level. Internet Explorer may occur. Generally, no suicide node is used. parentNode. removeChild (node); // delete its child from the parent node. Generally, alert ("aa ");}
- Replace the one that is not retained
Function remove2 () {var node1 = document. getElementById ("p_id1"); var node2 = document. getElementById ("p_id2"); // node1.replaceNode (node2); // replace a child with a parent node: replace node2 node1.parentNode with node1. replaceChild (node1, node2); // object. replaceChild (oNewNode, oChildNode )}
Function clone () {var node1 = document. getElementById ("p_id1"); var node2 = document. getElementById ("p_id2"); var node1_2 = node1.cloneNode (true); // false: only the basic node can be cloned. The following subnode is not cloned. // an object is cloned, the default value is false. When the parameter is true, the child node is connected to clone node1.parentNode. replaceChild (node1_2, node2 );}
:
All source code:
DOM_operation.html