No announcement
 

Document Object Model (DOM) and DOM Operations

The Document Object Model (DOM) is a programming interface provided by web browsers that allows JavaScript to interact with the elements of an HTML document. It represents the structure of a web page as a tree of objects, where each object corresponds to an element, attribute, or text content in the document.

Example - DOM: Selecting, Modifying, Creating, and Removing Elements:

dom_operations.html

<!DOCTYPE html>
<html>
<head>
  <title>DOM Manipulation Example</title>
</head>
<body>

<h2>DOM Manipulation:</h2>
<div id="myDiv">
  <p>Hello, <span id="spanElement">DOM</span>!</p>
</div>

<script>
// Selecting DOM Elements
let divElement = document.getElementById("myDiv");
let spanElement = document.getElementById("spanElement");

// Modifying DOM Elements
spanElement.textContent = "Document Object Model";
divElement.style.backgroundColor = "lightblue";

// Creating DOM Elements
let newElement = document.createElement("p");
newElement.textContent = "This is a new paragraph.";
divElement.appendChild(newElement);

// Removing DOM Elements
setTimeout(function() {
  divElement.removeChild(newElement);
}, 3000);
</script>

</body>
</html>

Output
DOM Manipulation: Hello, Document Object Model! This is a new paragraph.

After 3 seconds, the "This is a new paragraph." text will disappear.

Explanation:

  • The HTML code includes a <div> element with the id "myDiv". Inside the <div>, there's a paragraph (<p>) element containing the text "Hello, DOM!" and a <span> element with the id "spanElement" enclosing the word "DOM".
  • The JavaScript code selects elements using document.getElementById() and modifies their content using the textContent property and style using the style property.
  • We create a new paragraph (<p>) element using document.createElement("p"), set its content using the textContent property, and append it to the <div> using divElement.appendChild(newElement).
  • After 3 seconds, we remove the newly created paragraph using divElement.removeChild(newElement).

DOM manipulation allows JavaScript to dynamically update the content and appearance of web pages, making them interactive and responsive to user actions. It's a fundamental skill for web development, enabling the creation of dynamic user interfaces and the management of content on web pages.