DOM Intro

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

DOM Intro

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

Changing HTML Content

The easy way to modify the content of an HTML element is by make use of the innerHTML property.

To alter the content of an HTML element, use this syntax-

document.getElementById(id).innerHTML = new HTML

This example changes the content of a <p> element.

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

Hello World!

The paragraph above was changed by a script.

Example explained-

The HTML document above consists a <p> element with id=”p1″

Use the HTML DOM to get the element with id=”p1″

A JavaScript changes the content (innerHTML) of that element to “New text!”

This example changes the content of an <h1> element.

Example

<!DOCTYPE html>

<html>

<body>

<h2 id=”id01″>Old Heading</h2>

<script>

const element = document.getElementById(“id01”);

element.innerHTML = “New Heading”;

</script>

<p>JavaScript changed “Old Heading” to “New Heading”.</p>

</body>

</html>

Output

Old Heading

JavaScript changed "Old Heading" to "New Heading".

Changing the Value of an Attribute

To change the value of an HTML attribute, use this syntax.

document.getElementById(id).attribute = new value

This example changes the value of the src attribute of an <img> element.

Example

Let’s go slowly and learn how to use it.

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript HTML DOM</h2>

<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 HTML DOM

The original image was smiley.gif, but the script changed it to landscape.jpg

Example explained –

The HTML document above consists of an <img> element with id=”myImage”.

Use the HTML DOM to get the element with id=”myImage”

A JavaScript alters the src attribute of that element from “smiley.gif” to “landscape.jpg”,

Dynamic HTML content

JavaScript is used to create dynamic HTML content.

<!DOCTYPE html>

<html>

<body>

<p id=”demo”></p>

<script>

document.getElementById(“demo”).innerHTML = “Date : ” + Date();

</script>

</body>

</html>

Output

document.write()

In JavaScript, document.write()writes directly to the HTML output stream.

Example

<!DOCTYPE html>

<html>

<body>

<p>Bla, bla, bla</p>

<script>

document.write(Date());

</script>

<p>Bla, bla, bla</p>

</body>

</html>

Output

Bla, bla, bla

Bla, bla, bla