JS-DOM object
I. concept
1. DOM: Document Object Model Document Object Model
In order to achieve the dynamic interaction effect of the page, bom operation is far from enough, and html operation is the core. How to operate htm is dom. Simply put, dom
The dynamic control of html interface with program is provided. DOM (Document Object Model) describes a hierarchical tree of nodes that runs to add, remove, and modify a part of a page. DOM is at the core of javascript.
Each HTML document loaded into the browser becomes a Document object. Document objects allow us to access all elements in HTML pages from scripts. Document objects are part of Windows objects and can be accessed through the window.document attribute.
2, node
When loading an HTML page, the Web browser generates a tree structure to represent the internal structure of the page. DOM interprets this tree structure as consisting of nodes and forming a node tree. For the elements in the page, it can be decomposed into the following types of nodes: document node, element node, attribute node, text node, annotation node.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>tree!tree!Trees are everywhere.!</title> </head> <body> <div title="Attribute node">test Div</div> </body> </html>
HTML - > Document Node
Div - > element node
Title - > attribute node
Test Div - > Text Node
II. Operation of Element Nodes
1. Getting Nodes
When we add, delete and change, we need to specify a location or find a target. At this time, we can find and locate an object (that is, the node) through the method provided by the Document object.
Note: The operation dom must wait for the node to initialize before it can be executed. There are two ways to deal with it:
a. Move the script call tag to the end of html.
b. Use onload event to process JS, wait for html to load and then load the JS in onload event.
<!--according to idclass Get elements--> <p id="p1" class="paragraph">This is a paragraph.<span>text</span></p> <p id="p2" class="paragraph">This is another paragraph.</p> <!--according to name Get elements--> <input type="text" name="txt"/> <input type="checkbox" name="hobby" value="Swimming" />Swimming <input type="checkbox" name="hobby" value="Basketball" />Basketball <input type="checkbox" name="hobby" value="Football" />Football <hr/> <!--Get elements by tag name--> <!--href="javascript:void(0)": A pseudo-protocol that implies that a specified click event is executed instead of a jump. --> <a href="javascript:void(0);" "testById();">according to id Get elements</a> <a href="javascript:void(0);" "testByName();">according to name Get elements</a> <a href="javascript:void(0);" "testByTagName();">Get elements by tag name</a> <a href="javascript:void(0);" "testByClass();">according to class Get elements</a> <script type="text/javascript"> //Get elements based on id function testById(){ //Returns a single object var p = document.getElementById("p1"); console.log(p); console.log(p.innerHTML);// Represents the html structure between the start tag and the end tag of the fetched element console.log(p.innerText);// Represents plain text between retrieved Tags } //Get elements by name function testByName(){ //Returns an array of objects var hobby = document.getElementsByName("hobby"); console.log(hobby); for(var i = 0; i < hobby.length; i++) { console.log(hobby[i].value); } } //Get elements by tag name function testByTagName(){ //Returns an array of objects var input_arr = document.getElementsByTagName("input"); for(var i = 0; i < input_arr.length; i++) { if(input_arr[i].type== "text") { console.log("text type"); } else if(input_arr[i].type == "checkbox") { if(input_arr[i].checked){ console.log(input_arr[i].value); } } } } //Get elements by class function testByClass(){ //Returns an array of objects var paragraph = document.getElementsByClassName("paragraph"); console.log(paragraph[0].innerHTML); paragraph[0].innerHTML+= ",This is a new text."; } </script>
2. Create and insert nodes
There are several ways to create nodes:
Method | describe |
---|---|
createElement() | To create a new node, you need to pass in the label name of the node and return the created element object. |
createTextNode() | Create a text node that can pass in text content |
innerHTML | It also achieves the effect of creating nodes and adding them directly to the specified location. |
There are several ways to insert nodes:
Method | describe |
---|---|
write() | Insert any string into the document |
appendChild() | Add a new child node to the element as the last child node |
insertBefore() | Insert a new node before the specified existing node |
//Create node var div=document.createElement("div"); console.log(div); div.style.width="700px"; div.style.height="100px"; div.style.background="pink"; //Create a p-Label node var p=document.createElement("p"); //First kind p.innerHTML="It's a bit fine today.~~~"; p.innerText="It's a little hot today.~~"; //Second kinds var text= document.createTextNode("Today is Wednesday"); //Insert node appendChild() to append element and append element at last position in parent node //Parameter: Node to insert //Subject: parent node return value: additional node p.appendChild(text); console.log(p); div.appendChild(p); //Third kinds //Div.innerHTML="<p>Wang Sicong is a little handsome!</p>";//Identify html tag structure div.innerText="<p>Wang Sicong is a little handsome.!</p>"; //Text recognition //Insert node insertBefore (child Node1, child Node2) //Parameter: Specified child node in ChildNode2 parent node to be inserted by ChildNode1 //Subject: parent node return value: return the first parameter, the node to insert //Note: The value of the ChildNode2 parameter is null,undefined, which implements the additional effect. //Specify the location before appending div to img console.log(document.body.insertBefore(div,document.getElementById("img")));
3. Indirect Finding Nodes
Method/attribute | describe |
---|---|
childNodes | An array of child nodes returning elements |
firstChild | Returns the first child node of the element |
lastChild | Returns the last child node of the element |
nextSibling | Returns the next sibling node of the element |
parentNode | Returns the parent node of the element |
previousSibling | Returns the last sibling node of the element |
<div id="box"> <div>I am big brother.</div> <div class="er">I am the second brother. <p>I am p1</p> <p>I am p2</p> <p>I am p3</p> </div> <div>I am the third brother.</div> </div> <script> var div2=document.getElementsByClassName("er")[0]; //childNodes An array of child nodes that return elements includes text nodes console.log(div2.childNodes); //All child nodes console.log(div2.children); //Element node //First Child returns the first child of the element console.log(div2.firstChild); //Text node //lastChild returns the last child node of the element console.log(div2.lastChild); //Text node //The last and last element subnode console.log(div2.firstElementChild); //p1 console.log(div2.lastElementChild); //p3 //nextSibling returns the next sibling node of the element console.log(div2.nextSibling); //previousSibling returns the previous sibling node of the element console.log(div2.previousSibling); //Last | Next element sibling node console.log(div2.nextElementSibling); console.log(div2.previousElementSibling); //parentNode returns the parent node of the element console.log(div2.parentNode); </script>
4. Replacement Nodes
Method/attribute | describe |
---|---|
replacedChild(newNode,oldNode) | Replace old nodes with new ones |
The first is to get the parent node and replace the old node with the new one.
Parent node. replaceChild(newNode, oldNode);
The second is to locate the parent node through the old node, and then replace the old node with the new node.
oldNode.parentNode.replaceChild(newNode, oldNode);
<div id="dv"> <button type="button" id="btn">I am a button</button><br /> <button type="button" "replace_child();">replace</button> </div> <script type="text/javascript"> function replace_child() { // The first way is to get the parent node and replace the old node with the new one. // Get the button element var btn = document.getElementById('btn'); // Create the p element var p = document.createElement('p'); p.innerText = 'I am a paragraph'; // Get the parent div and replace the button element with the p element var dv = document.getElementById('dv'); dv.replaceChild(p, btn); // The second way is to locate the parent node through the old node, and then replace the old node with the new one. // Replace button element with p element // btn.parentNode.replaceChild(p, btn); } </script>
5. Cloning Node
Method/attribute | describe |
---|---|
cloneNode() | Replication node |
var replicated node = replicated node. cloneNode([true/false]);
true: deep cloning, cloning structure and content
False (default): clone only structure
<ul id="ul"> <li>Fan Bingbing</li> <li>Huo Siyan</li> <li>Cai Xu Kong</li> </ul> <input type="button" id="btn" value="Clone"> <input type="button" id="btn2" value="delete"> <script> var ul=document.getElementsByTagName("ul")[0]; var btn=document.getElementById("btn"); var btn2=document.getElementById("btn2"); var li2=document.getElementsByTagName("li")[2]; ul.function(){ ul.style.background="yellow"; }; /* Clone Node (boolean) Parameters: true: The child nodes are also cloned. false: Clone only the structure of the current node, excluding the default false of the child node Subject: Return value of node to be cloned: Return node to be cloned Note: js code will not be cloned If the id attribute exists in the original node, manually modify the id of the new node */ btn.function(){ var newNode=ul.cloneNode(true); console.log(document.body.appendChild(newNode)); };
6. Delete Nodes
Method | attribute |
---|---|
removeChild() | Remove child nodes from elements |
First: Get the parent node and delete the child node
Parent node. removeChild (child Node);
The second is to locate the parent node through the old node, and then delete the child node.
childNode.parentNode.removeChild(childNode);
<div id="del_dv"> <span id="programmer">code monkey</span> <a href="javascript:void(0)" "delNode();">delete</a> </div> <script type="text/javascript"> function delNode() { // The first way: Get the parent node, and then delete the child node var dv = document.getElementById('del_dv'); var programmer = document.getElementById("programmer"); dv.removeChild(programmer); // The second way is to locate the parent node through the old node, and then delete the child node. // var programmer = document.getElementById("programmer"); // programmer.parentNode.removeChild(programmer); } </script>
The results are as follows:
7. Operation Form
Method | describe |
---|---|
submit() | Submit (onsubmit event is started by default when submit is clicked) |
reset() | Reset (the onreset event is started by default when you click reset) |
<form action=""> <p> //User name: <input type="text" name="username" value="zhangsan"> </p> <p>Password: <input type="pwd" name="pwd"></p> <p> //Gender: <input type="radio" name="sex" value="nan">span>male</span> <input type="radio" name="sex" value="nv" checked><span>female</span> </p> <p> //Hobbies: <input type="checkbox" name="interest" value="singing">singing <input type="checkbox" name="interest" value="dancing"> dance <input type="checkbox" name="interest" value="rap"> sing rap </p> //Hometown: <select name="area" id="> <option value="hegang">Hegang</option> <option value="tongling">Tongling</option> <option value="yancheng" selected>ynz</option> </select> <p> <input type="submit"> <input type="reset" value="Reset"> <input type="button" value="Button" name="btn"> </p> </form> <script> /* * Form elements: * All nodes can be retrieved according to the dom * Special access: form node. name * * Form element time: * onchange Content Change Starting Event * oninput Content has input start event * * form Event * onsubmit() * onreset() * * form Method * submit() * reset() * */ var form=document.getElementsByTagName("form")[0]; console.log(form.username.value); console.log(form.sex.value); //array var sexs=form.sex; //Traversing through all gender nodes for(var i=0;i<sexs.length;i++){ if(sexs[i].checked){ sexs[i].nextElementSibling.style.color="red"; } } //select console.log("select Value:"+form.area.value); console.log(form.area.options[0],form.area.options[0].selectedIndex); console.log(form.area.selectedIndex); //Index of selected options form.username.function(){ console.log("Start typing in"); }; //Defocus + Change of Content to Trigger form.pwd.function(){ console.log("Content changed"); }; form.function(){ console.log("Form to be submitted"); }; form.function(){ console.log("Reset"); }; form.btn.function(){ console.log("Make preparation,I have to submit it it."); // form.submit(); form.reset(); } </script>
The results are as follows: