Home  >  Article  >  Web Front-end  >  How to change text content with javascript

How to change text content with javascript

青灯夜游
青灯夜游Original
2021-05-18 15:59:3713263browse

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. .

How to change text content with javascript

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>

How to change text content with javascript

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn