HTML CSS JAVASCRIPT PYTHON JAVA

JavaScript DOM

The DOM (Document Object Model) is a programming interface for web pages. It represents the structure of an HTML document as objects that JavaScript can access and modify.

With the DOM, JavaScript can change HTML content, styles, and attributes dynamically.

What is the DOM?

When a web page is loaded, the browser creates a Document Object Model of the page. This model allows JavaScript to interact with all elements of the page.

Accessing HTML Elements

You can access HTML elements using different methods. The most common method is getElementById().

Example
<!DOCTYPE html>
<html>
<body> 
<p id="dom1">Hello</p>

<button onclick="
document.getElementById('dom1').innerHTML = 'Hello JavaScript';
">Click Me</button>
</body>
</html> 
Try this code

Changing HTML Content

JavaScript can change the content of HTML elements using the innerHTML property.

Example
<!DOCTYPE html>
<html>
<body> 
<p id="dom2">Original Text</p>

<button onclick="
document.getElementById('dom2').innerHTML = 'Updated Text';
">Change Text</button>
</body>
</html>
Try this code

Changing CSS Styles

JavaScript can also change the style of HTML elements.

Example
<!DOCTYPE html>
<html>
<body> 
<p id="dom3">Styled Text</p>

<button onclick="
document.getElementById('dom3').style.color = 'red';
">Change Color</button>
</body>
</html>
Try this code

Changing Attributes

You can change HTML attributes such as images or links using JavaScript.

Example
<!DOCTYPE html>
<html>
<body> 
<img id="domImg" src="image1.jpg" width="100">

<button onclick="
document.getElementById('domImg').src = 'image2.jpg';
">Change Image</button>
</body>
</html>
Try this code

Adding Elements

JavaScript can create new HTML elements and add them to the page.

Example
<!DOCTYPE html>
<html>
<body> 
<div id="container"></div>

<button onclick="
let p = document.createElement('p');
p.innerHTML = 'New Paragraph';
document.getElementById('container').appendChild(p);
">Add Element</button>
</body>
</html> 
Try this code

Removing Elements

JavaScript can also remove elements from the page.

Example
<!DOCTYPE html>
<html>
<body> 
<p id="removeMe">Remove me</p>

<button onclick="
document.getElementById('removeMe').remove();
">Remove</button>
</body>
</html> 
Try this code

Why the DOM is Important