通过 js 修改 html 的文本内容或者样式

通过 js 修改 html 的文本内容

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>xiao001</title>
 6 </head>
 7 <body>
 8     <h1>this is a js and html code</h1>
 9     <p id = "demo">点击按钮将此处文本替换</p>
10     <button type="button" onclick="my_function()">点我</button>
11 
12     <script type="text/javascript">
13         function my_function() {//替换demo里面的文本内容
14             document.getElementById("demo").innerHTML = "Hello javascript!";
15         }
16     </script>
17 
18 </body>
19 </html>
View Code

同时我们可以发现,只要在对应 id 所在标签所包含的文本都会被替换,包括其下级标签包含的内容

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>xiao001</title>
 6 </head>
 7 <body>
 8     <h1>this is a js and html code</h1>
 9     <div id = "demo">
10         <ul>
11             <li>first</li>
12             <li>second</li>
13             <li>third</li>
14         </ul>
15         <p>this will be replace too</p>
16     </div>
17     <button type="button" onclick="my_function()">点我</button>
18 
19     <script type="text/javascript">
20         function my_function() {//替换demo里面的文本内容
21             document.getElementById("demo").innerHTML = "Hello javascript!";
22         }
23     </script>
24 
25 </body>
26 </html>
View Code

通过 js 修改 html 样式

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>xiao001</title>
 6 </head>
 7 <body>
 8     <p id="demo">change the color of this paragraph</p>
 9     <button type="button" onclick="my_function()">do it</button>
10 
11     <script type="text/javascript">
12         function my_function() {
13             var cnt = document.getElementById('demo');//找到元素
14             cnt.style.color = "#ff0000";//改变样式
15         }
16     </script>
17 </body>
18 </html>
View Code

同理,只要在对应 id 所在标签所包含的样式都会做出对应变化,包括其下级标签中的样式

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>xiao001</title>
 6 </head>
 7 <body>
 8     <div id="demo">
 9         change the color of this paragraph
10         <ul>
11             <li>one</li>
12             <li>two</li>
13             <li>three</li>
14         </ul>
15     </div>
16     <button type="button" onclick="my_function()">do it</button>
17 
18     <script type="text/javascript">
19         function my_function() {
20             var cnt = document.getElementById('demo');//找到元素
21             cnt.style.color = "#ff0000";//改变样式
22         }
23     </script>
24 </body>
25 </html>
View Code
原文地址:https://www.cnblogs.com/geloutingyu/p/9402346.html