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

How to change text content with javascript

青灯夜游
Release: 2023-01-06 11:13:56
Original
13353 people have browsed it

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
Copy after login

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>
Copy after login

How to change text content with javascript

Find the element's Method:

1. Get the element based on the id

document.getElementById("id属性的值");
Copy after login

2. Get the element based on the tag name

document.getElementsByTagName("标签的名字");
Copy after login

3. Get the element based on the value of the name attribute

document.getElementsByName("name属性的值");
Copy after login

4. Get elements based on the class attribute

document.getElementsByClassName("类样式的名字");
Copy after login

5. Get elements based on the css path (get one)

document.querySelector("css路径");
Copy after login

6. Get elements based on the css path (get a group)

document.querySelectorAll("css路径");
Copy after login

【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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template