/    /  Javascript DOM- HTML

Javascript DOM- HTML

 

The HTML DOM provides JavaScript to change the content of HTML elements.

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

 

Example:

 

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

 

OUTPUT:

 

Wed Feb 17 2021 09:49:21 GMT+0530 (India Standard Time)
Never use document.write() after the document is loaded. It will overwrite the document.

 

Changing HTML Content:

 

To change the content of an HTML element(using the innerHTML property.):

 

syntax:

 

document.getElementById(id) = new HTML

 

Example:

 

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript can Change HTML</h2>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>

 

OUTPUT:

 

JavaScript can Change HTML
New text!
The paragraph above was changed by a script.

 

Changing the Value of an Attribute:

 

To change the values

 

syntax:

 

document.getElementById(id).attribute = new value

 

Example:

 

<!DOCTYPE html>
<html>
<body>
<img id="image" src="smiley.gif" width="160" height="120">
<script>
document.getElementById("image").src = "landscape.jpg";
</script>
<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>
</body>
</html>

 

OUTPUT:

 

Javascript DOM- HTML