How to change text content in JavaScript: First use the "document.getElementById(id value)" statement to obtain the text element object; then use the "text element object.innerHTML= "new text content"" statement to modify it. .
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Change HTML content
The easiest way to modify the content of an HTML document is to use the innerHTML attribute.
To modify the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML = new text
Example:
<!DOCTYPE html> <html> <body> <h2>JavaScript 可以更改 HTML</h2> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML = "Hello Kitty!"; </script> <p>上面的段落由脚本更改。</p> </body> </html>
Find the element's Method:
1. Get the element based on the id
document.getElementById("id属性的值");
2. Get the element based on the tag name
document.getElementsByTagName("标签的名字");
3. Get the element based on the value of the name attribute
document.getElementsByName("name属性的值");
4. Get elements based on the class attribute
document.getElementsByClassName("类样式的名字");
5. Get elements based on the css path (get one)
document.querySelector("css路径");
6. Get elements based on the css path (get a group)
document.querySelectorAll("css路径");
【Recommended learning: javascript advanced tutorial】
The above is the detailed content of How to change text content with javascript. For more information, please follow other related articles on the PHP Chinese website!