[JavaScript Practical Tips (2)] Js Manipulates DOM (Problem-provoked article revamps, newbies can either)
Blog Description
The information in this article comes from the Internet and personal summary, which is intended to summarize personal learning and experience. If there is any infringement, please contact me to delete it. Thank you!
Explain
The source of this article is a change of the previous note, which is to get js to get the value of the input tag, which was just an example at that time. Of course, the following example remains, after all, it is an incremental requirement to care about the feelings of older users.
From an example at that time, there were still more points to summarize or learn.
New people may just want to solve a problem, and the big guys have trouble finding out where to add to the summary.
js gets the value inside the input tag
demand
Sometimes we need to get some values in the input, such as when sending a mobile phone authentication code, first write the following code in html
Code
html a simple input tag
<input type="text" name="name" id="phone" />
js Gets the value of the input tag
var phone = document.getElementById("phone").value;
Explain
Looking at the code above, you use the API of the DOM to get the value of the input tag. Now that it is available, the DOM also provides an API that can be changed or replaced, and the DOM can be executed in the JS, so the interaction between JS and HTML comes.
Once hooked up, there will be fewer patterns in the future?
So all kinds of template engines, responsive, JS animations don't just come in a crowd.
Whether something that feels deep is coming, don't worry, return to the topic, this chapter mainly talks about JS operation DOM.
JS capabilities
When talking about JS's ability to operate DOM, I feel it is necessary to talk about JS's ability first.
Below is the HTML DOM tree of the object from W3C. https://www.w3school.com.cn/j...
Through this object model, JavaScript gets all the power to create dynamic HTML:
- JavaScript can change all HTML elements in a page
- JavaScript can change all HTML properties on a page
- JavaScript can change all CSS styles on a page
- JavaScript can delete existing HTML elements and attributes
- JavaScript adds new HTML elements and attributes
- JavaScript can respond to all existing HTML events on a page
- JavaScript can create new HTML events in pages
Seeing the above, I feel like I will use js, you can do anything, you can change anything. Don't be seen by this product, or you will never be able to push down some demands.
DOM Understanding
Since JS operates on DOM, first of all, you need to be familiar with DOM. Just before you wrote an article about DOM, [Browser] Chat about DOM
Common methods of operating DOM
Method | describe |
---|---|
getElementById() | Returns an element with the specified ID. |
getElementsByTagName() | Returns a list of nodes (collections/arrays of nodes) containing all elements with the specified tag name. |
getElementsByClassName() | Returns a list of nodes containing all elements of the specified class name. |
appendChild() | Adds a new child node to the specified node. |
removeChild() | Delete child nodes. |
replaceChild() | Replace child nodes. |
insertBefore() | Inserts a new child node in front of the specified child node. |
createAttribute() | Create a property node. |
createElement() | Create element nodes. |
createTextNode() | Create a text node. |
getAttribute() | Returns the specified property value. |
setAttribute() | Sets or modifies the specified property to the specified value. |
Get DOM Nodes
getElementsByTagName(): Gets the element objects based on the element name. The return value is an array.
getElementsByClassName(): Gets the element objects based on the Class attribute values. The return value is an array.
getElementsByName(): Gets the element objects based on the name attribute value. The return value is an array.
The four most common ways to get Element s are
getElementById()
Gets the element object based on the id attribute value. The id attribute value is generally unique.
If you need to find a specific element in a document, the most effective method is getElementById(), which is the best way to manipulate a specific element in a document by giving it an ID attribute (otherwise why do you think it is called ById), giving it a unique name (in the document), and then you can use that ID to find the desired element.
Example:
<html> <head> <script type="text/javascript"> function getValue(){ var x = document.getElementById("test") alert(x.innerHTML) } </script> </head> <body> <h1 id="test" onclick="getValue()">My</h1> <p>Click on me to see the effect</p> </body> </html>
Effect:
Code parsing:
Get the node whose element id is test through getElementById, and print the text of the test node.
The following figure is the obtained html node
getElementsByClassName()
The getElementsByClassName() method returns a collection of elements in the document with all specified class names as NodeList objects.
The NodeList object represents an ordered list of nodes. NodeList objects allow us to access a node in the list by its index number (the index number starts with 0).
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> <style> .example { border: 1px solid black; margin: 5px; } </style> </head> <body> <div class="example"> <p>I'm the first</p> </div> <div class="example color"> <p>I'm the second</p> </div> <div class="example color"> <p>I'm the third</p> </div> <button onclick="myFunction()">Look at the effect</button> <script> function myFunction() { var x = document.getElementsByClassName("color"); x[0].style.backgroundColor = "red"; console.log(x) } </script> </body> </html>
Effect:
Code parsing:
Gets an object with a class attribute of "color" through getElementsByClassName, resulting in a NodeList object representing a collection of elements with a specified class name. The order of elements in a collection is sorted in the order in which they appear in the code. Set the background color to red for the first one.
Note: Internet Explorer 8 and earlier versions of IE do not support the getElementsByClassName() method
Insert DOM Node
There are two ways to insert nodes, and their meanings are different.
appendChild()
A new child node is inserted at the end of the parent node.
Parent Node.appendChild(New Child Node);
insertBefore()
- Insert a new node before the reference node.
- If the reference node is null, it will insert a child node at the end of the parent node.
Parent Node.insertBefore(New Child Node,Child Node as Reference);
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body> <ul id="list"> <li>first</li> <li>Second</li> </ul> <p id="demo">Click the button to add the item to the list</p> <button onclick="myFunction1()">Click on me, add later</button> <button onclick="myFunction2()">Click on me, add before</button> <script> function myFunction1(){ var node = document.createElement("LI"); var textnode = document.createTextNode("I'm NEW"); node.appendChild(textnode); document.getElementById("list").appendChild(node); } function myFunction2(){ var node = document.createElement("LI"); var textnode = document.createTextNode("I'm NEW"); node.appendChild(textnode); var list = document.getElementById("list") list.insertBefore(node, list.childNodes[0]); } </script> </body> </html>
Effect:
Delete Node
removeChild()
You must specify which child node to delete
Parent Node.removeChild(Child Node);
If you need to delete the node itself
node.parentNode.removeChild(node);
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body> <ul id="list"> <li>first</li> <li>Second</li> </ul> <p id="demo">Click the button to add the item to the list</p> <button onclick="myFunction1()">Click on me, add later</button> <button onclick="myFunction2()">Click on me, add before</button> <button onclick="myFunction3()">Click on me to delete the first node</button> <script> function myFunction1(){ var node = document.createElement("LI"); var textnode = document.createTextNode("I'm NEW"); node.appendChild(textnode); document.getElementById("list").appendChild(node); } function myFunction2(){ var node = document.createElement("LI"); var textnode = document.createTextNode("I'm NEW"); node.appendChild(textnode); var list = document.getElementById("list") list.insertBefore(node, list.childNodes[0]); } function myFunction3(){ var list = document.getElementById("list") list.removeChild(list.childNodes[0]); } </script> </body> </html>
Effect:
Copy Node (Clone Node)
cloneNode()
Clone Node
Node to copy.cloneNode(); Node to copy.cloneNode(true);
Brackets with no parameters have different effects.
- No parameters/no parameters false: copy only the node itself, not the child nodes.
- true with parameters: replicates both the node itself and all its children.
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body> <ul id="list"> <li>first</li> <li>Second</li> </ul> <button onclick="myFunction()">Click on me, clone node</button> <script> function myFunction(){ var itm = document.getElementById("list"); var cln = itm.cloneNode(true); document.getElementById("list").appendChild(cln); } </script> </body> </html>
Effect:
Setting the properties of a node
Mainly also get, modify, and delete
Get the attribute value of a node
Element Node.attribute; Element Node[attribute]; node.getAttribute("Property Name");
The former is to manipulate labels directly, and the latter is to use labels as DOM nodes.
Set the value of a node's properties
myNode.src = "xxxx" //Modify the attribute value of src myNode.className = "xxxx"; //Modify class name Element Node.setAttribute(Property Name, New Attribute Value);
The former is to manipulate labels directly, and the latter is to use labels as DOM nodes.
Delete the properties of a node
Element Node.removeAttribute(Property Name);
summary
DOM nodes are recommended instead of directly manipulating labels.
Thank
Universal Network
And a hard-working self, Personal Blog,GitHub Test,GitHub
Public Number - Guizimo, Applet - Xiaogui Blog