通過 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM