JavaScript html dom-change HTML and javascriptdom
Change the HTML output stream
JavaScript can create dynamic HTML content:
Today's date is: Mon Jan 25 2016 15:22:41 GMT + 0800 (China Standard Time)
In JavaScript, document. write () can be used to directly output the stream content to HTML.
Instance
<! DOCTYPE html>
<Html>
<Body>
<Script>
Document. write (Date ());
</Script>
</Body>
</Html>
|
Never use document. write () after the document is loaded (). This will overwrite this document. |
Change HTML content
Use the innerHTML attribute when modifying HTML content in the simplest way.
To change the content of HTML elements, use this syntax:
Document. getElementById (Id). InnerHTML =New HTML
In this example, the content of the <p> element is changed:
Instance
<Html>
<Body>
<P id = "p1"> Hello World! </P>
<Script>
Document. getElementById ("p1"). innerHTML = "New text! ";
</Script>
</Body>
</Html>
In this example, the content of the
Instance
<! DOCTYPE html>
<Html>
<Body>
<H1 id = "header"> Old Header
<Script>
Var element = document. getElementById ("header ");
Element. innerHTML = "New Header ";
</Script>
</Body>
</Html>
Example:
- The preceding HTML document contains the
- We use html dom to obtain the id = "header" element.
- JavaScript changes the content of this element (innerHTML)
Change HTML attributes
To change the attributes of HTML elements, use this syntax:
Document. getElementById (Id).Attribute = new value
In this example, the src attribute of the element is changed:
Instance
<! DOCTYPE html>
<Html>
<Body>
<Script>
Document. getElementById ("image"). src = "landscape.jpg ";
</Script>
</Body>
</Html>