Js_ updating the DOM

Source: Internet
Author: User

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" >&lt;script&gt;alert ("Hi") &lt;/script&gt;</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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.