The best JavaScript HTML DOM changes HTML content Tutorial In 2024, In this tutorial you can learn Change the HTML output stream,Examples,Change the HTML content,Examples,Examples,Change the HTML attributes,Examples,

JavaScript HTML DOM changes HTML content

HTML DOM allows JavaScript to change the content of the HTML element.


Change the HTML output stream

JavaScript can create dynamic HTML content:

Today's date is:Sun Sep 26 2021 22:56:33 GMT+0800 (中国标准时间)

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

Examples

<!DOCTYPE html>
<html>
<body>

<script>
document.write(Date());
</script>

</body>
</html>


lamp Never use document.write after the document has finished loading (). This overrides the document.


Change the HTML content

Using innerHTML property The easiest way to modify the HTML content.

To change the content of the HTML element, use this syntax:

document.getElementById(id).innerHTML=新的 HTML

This example changes the contents of the <p> element:

Examples

<Html>
<Body>

<P id = "p1"> Hello World! </ P>

<Script>
document.getElementById ( "p1") innerHTML = "new text!.";
</ Script>

</ Body>
</ Html>

This example changes the contents of the <h1> element:

Examples

<!DOCTYPE html>
<html>
<body>

<h1 id="header">Old Header</h1>

<script>
var element=document.getElementById("header");
element.innerHTML="新标题";
</script>

</body>
</html>

Examples to explain:

  • The above HTML document that contains id = "header" of the <h1> element

  • We use the HTML DOM to get the id = "header" element

  • JavaScript changes on this element contents (innerHTML)


Change the HTML attributes

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

document.getElementById(id).attribute=新属性值

This example changes the src attribute <img> element:

Examples

<!DOCTYPE html>
<html>
<body>

<img id="image" src="smiley.gif">

<script>
document.getElementById("image").src="landscape.jpg";
</script>

</body>
</html>

Examples to explain:

  • The above HTML document that contains id = "image" of the <img> element
  • We use the HTML DOM to get the id = "image" element
  • JavaScript change the properties of this element (the "smiley.gif" to "landscape.jpg")
JavaScript HTML DOM changes HTML content
10/30