JavaScript Essentials (10) HTML DOM-changing HTML

Source: Internet
Author: User

The HTML DOM allows JavaScript to change the contents of an HTML element.

A. Change the HTML output stream

JavaScript is able to create dynamic HTML content:

Today's date is: Thu Oct 11:14:18 gmt+0800 (CST)

In JavaScript, document.write () can be used to write content directly to the HTML output stream.

?? <! DOCTYPE html>document.write (Date ()); </script></body>

?? Never use document.write () after the document has finished loading. This overwrites the document.

B. Change HTML Content

The simplest way to modify HTML content is to use the InnerHTML property.

To change the contents of an HTML element, use this syntax:

document.getElementById (ID). innerhtml= new HTML
 1  This example changes the <p> 2  3  <p id= "P1" >hello world!</p> 4  6  document.getElementById ("P1"). innerhtml= "New text!"  7  </script> 
1 This example changes the contents of the   2 <! DOCTYPE html> 3  4 <body> 5  6 

7 8 <script> 9var element=document.getelementbyid ("header" ); Ten element.innerhtml= "new title"; </script> </body>

Explain:

    1. The above HTML document contains the
    2. Use HTML DOM to get id= "header" elements
    3. JavaScript changes the contents of this element (InnerHTML)

C. Change HTML Properties

To change the attributes of an HTML element, use this syntax:

document.getElementById (ID). attribute= new Attribute value

This example changes the SRC attribute of the element:

1 <! DOCTYPE html> 2  3 <body> 4  5  6  7 <script> 8 document.getElementById (" image "). src=" Landscape.jpg "; 9 </script> </body> 

Example Explanation:

    • The above HTML document contains the elements of the id= "image"
    • We use the HTML DOM to get the elements of the id= "image"
    • JavaScript changes the attributes of this element (change "smiley.gif" to "landscape.jpg")

JavaScript Essentials (10) HTML DOM-changing HTML

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.