DOM Basics πŸš€ | JavaScript Journey | In Hindi | Death Code - DeathCode

Understanding the HTML DOM in JavaScript

What is the DOM?

The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of objects that can be manipulated using JavaScript. This allows developers to dynamically change the content, structure, and style of a webpage.

Why Use the DOM?

  • To dynamically update content on a webpage without reloading.
  • To create interactive and responsive web applications.
  • To access and manipulate HTML elements programmatically.

Common DOM Methods

1. document.getElementById()

Retrieves an element by its ID.

const h1 = document.getElementById("heading");
h1.style.color = "#fff"; // Changes text color to white

2. document.querySelector()

Returns the first element that matches a CSS selector.

const para = document.querySelector("#para");
console.log(para.innerText); // Logs visible text of the paragraph

3. document.querySelectorAll()

Returns a NodeList of all elements matching a CSS selector.

const allParagraphs = document.querySelectorAll("p");
allParagraphs.forEach((p, index) => {
    console.log(`Paragraph ${index + 1}:`, p.textContent);
});

4. document.getElementsByClassName()

Retrieves all elements with a specified class name.

const highlighted = document.getElementsByClassName("highlight");
console.log(highlighted[0]); // Logs the first element with class 'highlight'

5. Manipulating the Document Title

document.title = "Death Code DOM Tutorial";

6. Adding a New Element

We can dynamically create and add new elements to the DOM.

const newPara = document.createElement("p");
newPara.textContent = "This is a dynamically added paragraph.";
document.body.appendChild(newPara);

Additional Tips

  • Always use querySelector or querySelectorAll for modern projects as they are more versatile.
  • Use innerText for visible text and textContent for all text, including hidden content.
  • Manipulate styles dynamically using the style property.
  • Use createElement and appendChild to add new elements to your webpage.
Β© 2024 DeathCode. All Rights Reserved.