Getting or replacing html content with innerHTML in javascript

Posted by xadmin on Tue, 17 Mar 2020 15:42:14 +0100

The innerHTML attribute is used to get or replace the content of HTML elements. The syntax is Object.innerHTML
Among them, 1.Object is the obtained element object, such as the element obtained through document.getElementById("ID"); 2. Pay attention to writing, innerHTML is case sensitive.
We get the < div > element through id="light", and output and change the content of the element. The code is as follows:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title>innerHTML attribute</title>
 6     </head>
 7     <body>
 8         <div id="cshi">
 9             Hello, night 20200317
10         </div>
11         <!-- <script type="text/javascript">
12             var mylight=document.getElementById('light');
13             document.write('Original content:'+mylight.innerHTML+'<br/>');//Input element content
14             mylight.innerHTML='javascript tomorrow';//Modify element content
15             document.write('replace content:'+mylight.innerHTML);
16         </script> -->
17         <script type="text/javascript">
18             var mystr=document.getElementById('cshi');
19             mystr.innerHTML="DOM operation";
20             // document.write(mystr);
21         </script>
22     </body>
23 </html>

Get the h2 tag element through id, assign it to the variable mychar, and then use the innerHTML attribute to change the h2 tag content to "Hello world!"

 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>innerHTML</title>
 6 </head>
 7 <body>
 8 <h2 id="con">javascript</H2>
 9 <p> JavaScript Is a simple object-based, event driven scripting language embedded in HTML In the document, the browser is responsible for interpretation and execution, producing dynamic display effect on the web page and realizing the function of interaction with users.</p>
10 <script type="text/javascript">
11   var mychar= document.getElementById('icon');          ;
12   document.write("Original title:"+mychar.innerHTML+"<br>"); //Output source h2 Label content
13   mychar.innerHTML="Hello world!";
14   document.write("Modified title:"+mychar.innerHTML); //After output modification h2 Label content
15 </script>
16 </body>
17 </html>

Topics: Javascript Attribute