DOM
DOM
DOM
to interact with and modify the elements of a webpage. The DOM represents the
structure of a webpage as a tree of objects, where each node corresponds to a part
of the document, such as an element, attribute, or text. By manipulating the DOM,
you can change the content, structure, and style of a webpage dynamically after it
has been loaded in the browser.
The DOM represents the HTML document as a hierarchical tree of nodes. Each element
in the HTML document corresponds to a node in the DOM tree. For example, <html> is
the root node, and it contains child nodes like <head>, <body>, and so on.
Accessing DOM Elements:
To manipulate the DOM, you first need to select the elements you want to work with.
JavaScript provides various methods to access DOM elements.
javascript
Copy code
// Select by ID
let element = document.getElementById('elementId');
You can change the inner content of an HTML element using innerHTML, textContent,
or by directly modifying the DOM tree.
javascript
Copy code
let element = document.getElementById('myElement');
element.innerHTML = 'New HTML content'; // Sets HTML content
element.textContent = 'Just text'; // Sets plain text content
Changing Attributes:
You can modify the attributes of an HTML element using setAttribute, getAttribute,
or directly by accessing the property.
javascript
Copy code
let img = document.querySelector('img');
img.setAttribute('src', 'newImage.jpg'); // Change the src attribute
let src = img.getAttribute('src'); // Get the src attribute
Changing Styles:
You can create new HTML elements using createElement and insert them into the DOM
using methods like appendChild, insertBefore, or replaceChild.
javascript
Copy code
let newDiv = document.createElement('div');
newDiv.textContent = 'This is a new div';
document.body.appendChild(newDiv); // Adds the new div to the end of the body
Removing Elements:
You can remove elements from the DOM using removeChild or remove.
javascript
Copy code
let element = document.getElementById('myElement');
element.remove(); // Removes the element from the DOM
Event Handling:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation Example</title>
</head>
<body>
<p id="myParagraph">This is the original text.</p>
<button id="myButton">Click to change text</button>
<script>
// Access the button and paragraph elements
const button = document.getElementById('myButton');
const paragraph = document.getElementById('myParagraph');