innerHTML not only modifies the text content of the DOM node, but also modifies the subtree inside the DOM node directly from the HTML fragment.
// get <p id= "P-id" >...</p> var p = document.getElementById (' P-id '); // set Text to ABC: // <p id= "P-id" >ABC</p> // Set HTML:p.innerhtml = ' ABC <span style= ' color:red ' >RED</span> XYZ '; // the internal structure of <p>...</p> has been modified
(If the string being written is taken over the network, be aware of character encodings to avoid XSS attacks)
InnerText and Textcontent automatically HTML-encode strings to ensure that no HTML tags can be set
The difference is that innertext does not return the text of the hidden element, and Textcontent returns all the text. Ie<9 does not support textcontent
// get <p id= "P-id" >...</p> var p = document.getElementById (' P-id '); // set Text:P.innertext = ' <script>alert ("Hi") </script> '; // HTML is automatically encoded, unable to set a <script> node: // <p id= "P-id" ><script>alert ("Hi") </script></p>
Modifying the CSS can also be done through the DOM's style. If the font-size name does not conform to the JS valid attribute name, so need to write in JS the hump type name FontSize
// get <p id= "P-id" >...</p> var p = document.getElementById (' P-id '); // Set CSS:p.style.color = ' #ff0000 '= ' 20px '= ' 2em ';
Practice
<!--HTML structure--><div id= "Test-div" > <p id= "Test-js" >javascript</p> <p>java </p></div>
' Use strict '/Get <p>javascript</p> node:var js = document.getElementById (' Test-js '); // Modify the text to JavaScript: // TODO:js.innerhtml= ' JavaScript '; // Modify CSS to: color: #ff0000, Font-weight:bold // TODO:js.style.color= ' #ff0000 '; js.style.fontWeight= ' bold ';
Js_ updating the DOM