DOM object
< font color = "red" > DOM < / font >: 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 HTMs is dom. Simply put, DOM provides a program to dynamically control the html interface. DOM (document object model) describes a hierarchical tree of nodes that run developers to add, remove, and modify parts of a page. DOM is at the heart of javascript.
Each HTML Document loaded into the browser becomes a Document object. The Document object enables us to access all elements of an HTML page from within a script. The Document object is part of the Window object and can be accessed through the window.document Property to access it.
node
When an HTML page is loaded, the Web browser generates a tree structure to represent the internal structure of the page. DOM interprets this tree structure as a tree of nodes. The elements in the page can be resolved into the following types of nodes:
Node type HTML content for example Document node Document itself Entire document Element node All HTML elements <a>,<div>,<p> Attribute node Attributes within HTML elements id,href,name,class Text node Text within element hello Comment Nodes Comments in HTML <!-- -->HTML > document node
Div > element node
Title > attribute node
Test div > text node
<html> <head> <title>tree!tree!Trees are everywhere!</title> </head> <body> <div title="Attribute node">test Div</div> </body> </html>
Node of operation element
When the HTML document is parsed into a DOM tree, each node in it can be regarded as an object, we call it DOM object. For these objects, we can perform various operations, find a node object or a class of node objects, create a node object, add a node object at a certain location, or even delete it dynamically Node objects, these operations can make our page look dynamic. In the later stage, combining with events, we can make our page perform specific transformation at a specific time and under a specific event.
Get nodeWhen adding, deleting, or modifying, you need to specify a location or find a target. At this time, we can find and locate an object (that is, a node) through the method provided by the Document object.
< font color = "red" > note: the operation dom can only be executed after the node initialization. </font>
There are two ways to deal with it:
(1) move the script call tag to the end of html;
(2) use the onload event to process JS, wait for the html to load and then load JS in the onload event.
window.onload = function () { //Execute} after preloading html;
The acquisition method is as follows:
method describe getElementById() Get the dom object according to the id. if the id is repeated, the first one will prevail getElementsByTagName() Get dom object array based on tag name getElementsByClassName() Get dom object array according to style name getElementsByName() Get the dom object array according to the name attribute value, which is often used to get multiple values<body> <p id="p1">This is a paragraph<span>text</span></p> <p id="p1">This is another paragraph</p> <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 /> <a href="javascript:void(0)" onclick="testById()">according to id obtain</a> <a href="javascript:void(0)" onclick="testByName()">according to name obtain</a> <a href="javascript:void(0)" onclick="testByTagName()">Get by tag name</a> <a href="javascript:void(0);" onclick="testByClass();">according to class obtain</a> </body>
< font color = "red" > Description: href = "J avascript:void (0) ": pseudo protocol, which means that the specified click event is executed instead of jump. </font>
<script type="text/javascript"> // Get elements by id function testById() { // Return single object var p = document.getElementById("p1"); console.log(p); // Represents the html structure between the start tag and the end tag of the get element console.log(p.innerHTML); console.log(p.innerText); // Indicates to get normal text between tags } // Get elements by name function testByName() { // object array var ho = document.getElementsByName("hobby"); console.log(ho); for(var i = 0; i <= ho.length - 1; i++) { console.log(ho[i].value); } } // Get elements by tag name function testByTagName() { // object array var inputArr = document.getElementsByTagName("input"); for(var i = 0; i < inputArr.length; i++) { if(inputArr[i].type == "text") { console.log("text type"); } else if(inputArr[i].type == "checkbox") { if(inputArr[i].checked) { console.log(inputArr[i].value); } } } } // Get the element according to the class attribute function testByClass() { // object array var ps = document.getElementsByClassName("para"); console.log(ps[0].innerHTML); ps[0].innerHTML += "This is a new text"; } </script>Create and insert nodes
Many times we want to insert a new node in a certain location. At this time, we need to have a node first. We can create a new node in the following ways.
Create node 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 can also achieve the effect of creating nodes and directly add them to the specified location Insert node method describe write() Insert any string into the document appendChild() Add a new child to the element as the last child insertBefore() Insert a new node before the specified existing node newItem: the node to be inserted exsitingItem: the reference node needs to reference the parent node<button onclick="add()">Add paragraph</button> <div id="container"></div> <script type="text/javascript"> function add(){ var container = document.getElementById('container') var paragraph = document.createElement('p'); var txt = document.createTextNode('hello') paragraph.appendChild(txt) container.appendChild(paragraph) } </script>
Add paragraph, picture, text box, option
<body> <button onclick="addPara();">Add paragraph</button> <button onclick="addImg();">Add picture</button> <button onclick="addTxt();">Add text box</button> <button onclick="addOptions()">Add options</button> <select name="music"> <option value="-1">A song in your heart</option> <option value="0">Nanshan South</option> <option value="1">like you</option> </select> <hr /> <div id = "container"></div> </body>
<script type="text/javascript"> // Add p node function addPara(){ // Get container var container =document.getElementById("container"); // Create paragraph < p ></p> var p =document.createElement('p'); // The first way // Create text node var txt=document.createTextNode("In the future, you will thank you for your efforts"); // Append the txt node to the p node p.appendChild(txt); // Append the p node to the container node container.appendChild(p); /* // The second way // Add content to the p node p.innerHTML = "In the future, you will thank you for your efforts "; // Append the p node to the container node container.appendChild(p); */ /* // The third way // Add the p tag content of string type to the container without adding it more than once var str = "<p>In the future, you will thank you for your efforts now; container.innerHTML = str; */ } // Add picture function addImg(){ // create picture var img = document.createElement("img") ; /* // The first way to set properties // Set src attribute of img tag // img.src ="http://www.baidu.com/img/bd_logo1.png"; */ // Second way to set properties // The setAttribute() method adds the specified attribute and assigns it the specified value. // Set the src attribute of img img.setAttribute('src','http://www.baidu.com/img/bd_logo1.png'); img.style.width = '300px'; img.style.height = '200px'; // Get container var container =document.getElementById("container"); // Append the img node to the container. container.appendChild(img); } // Add text box function addTxt(){ // Create a text box var txt =document.createElement("input"); /* // Set type first method txt.type = "text"; txt.value = "Added successfully "; */ // Set type the second way txt.setAttribute('type', 'text'); txt.setAttribute('value', 'Successfully added'); /* * txt.type = 'password' * txt.value = '123' */ // Get container var container =document.getElementById("container"); // Append the txt node to the container. container.appendChild(txt); } // Add options for drop-down box function addOptions(){ // The first way /* // Create dropdown var option = document.createElement("option") ; option.value = "2" ; option.text = "Rape flower "; // Get dropdown var sel = document.getElementsByTagName("select")[0]; // Add drop-down sel.appendChild(option); */ // The second way: var option = document.createElement("option") ; option.value = "2" ; option.text = "Should not" ; // Get dropdown var sel = document.getElementsByTagName("select")[0]; // Add drop-down sel.options.add(option); // Third way: add drop-down item var sel = document.getElementsByTagName("select")[0]; sel.innerHTML += "<option value = '2'>hero</option>" ; } </script>Find nodes indirectly **Methods\ Properties** describe childNodes Returns an array of child nodes of an element firstChild Returns the first child of an element lastChild Returns the last child node of an element nextSibling Returns the next sibling of the element parentNode Returns the parent node of an element previousSibling Returns the last sibling of the element Delete node **Methods\ Properties** describe removeChild() Remove child nodes from element
<script type="text/javascript"> function delNode(){ var programmer =document.getElementById("programmer"); // Delete the node from the parent element, get the parent element of the object to be deleted, and then delete the object from the parent element programmer.parentNode.removeChild(programmer); } </script> <body> <span id="programmer">Cheng xuape</span> <a href="javascript:void(0)" onclick="delNode();">delete</a> </body>