๐ŸŒ JavaScript DOM & Browser BOM
Estimated reading: 4 minutes 291 views

JavaScript โ€“ DOM (Elements, Forms, Animations, Navigation): A Complete Guide


Introduction โ€“ Why Master the DOM?

Ever wondered how JavaScript changes webpages dynamicallyโ€”updates text, responds to form input, or animates elements? Thatโ€™s the power of the DOM (Document Object Model).

The DOM is your gateway to manipulating HTML and CSS with JavaScript. By the end of this guide, youโ€™ll learn:

  • How to access and manipulate DOM elements
  • Handle form inputs and validations
  • Animate HTML elements
  • Navigate the DOM tree

What is the DOM?

The Document Object Model (DOM) is a programming interface that represents an HTML or XML document as a tree structure, where each node is an object representing part of the page.

Example Tree:

<html>
  <body>
    <h1>Hello</h1>
    <p>World</p>
  </body>
</html>

JavaScript uses the DOM to interact with HTML/CSS in real time.


1. Accessing & Manipulating DOM Elements

You can use several methods to select and manipulate elements:

Common DOM Selectors

document.getElementById("header");
document.querySelector(".btn");
document.getElementsByClassName("item");
document.getElementsByTagName("div");

querySelector and querySelectorAll are preferred for flexibility.


Example: Change Text Content

document.getElementById("title").textContent = "Welcome!";

This updates the inner text of the element with ID title.


2. Forms & Input Handling

Handling forms is a critical part of DOM scripting.

Access Form Inputs

<input type="text" id="username" />
const name = document.getElementById("username").value;

Gets the value entered into the input field.


Validate Form Input

const email = document.getElementById("email");
if (!email.value.includes("@")) {
  alert("Invalid email");
}

Tip: Use addEventListener('submit', e => e.preventDefault()) to stop form submission during validation.


3. DOM Animations

DOM animations can be handled via:

  • CSS classes manipulated with JS
  • JavaScript setInterval() / setTimeout()
  • requestAnimationFrame() for smooth rendering

Example: Fading an Element

let box = document.getElementById("box");
let opacity = 1;

let fade = setInterval(() => {
  if (opacity <= 0) clearInterval(fade);
  box.style.opacity = opacity;
  opacity -= 0.1;
}, 100);

Gradually reduces the elementโ€™s opacity every 100ms.


4. DOM Navigation

You can traverse the DOM tree using node properties.

Key Navigation Properties

PropertyDescription
parentNodeAccess the parent element
childrenAccess child elements
nextElementSiblingNext sibling element
previousElementSiblingPrevious sibling
firstElementChildFirst child element
lastElementChildLast child element

Example: Navigate to Parent Node

let item = document.querySelector(".item");
let parent = item.parentNode;

Returns the parent of the element with class item.


Event Listeners on DOM Elements

Attaching event listeners is crucial for interactivity:

document.querySelector("button").addEventListener("click", () => {
  alert("Clicked!");
});

Binds a click event to the first <button> element.


Real-World Use Case: Form Submission with Validation

<form id="login">
  <input type="text" id="user" required />
  <button type="submit">Login</button>
</form>
document.getElementById("login").addEventListener("submit", (e) => {
  e.preventDefault();
  const user = document.getElementById("user").value;
  if (user.trim() === "") {
    alert("Username required");
  } else {
    console.log("Logging in:", user);
  }
});

Prevents default submission and validates the input before proceeding.


DOM vs Virtual DOM

FeatureDOMVirtual DOM
DefinitionActual page structureIn-memory representation
SpeedSlower with many updatesFaster with diffing algorithm
Used inVanilla JSLibraries like React

For performance, frameworks like React use a Virtual DOM to batch updates.


Tips & Best Practices

  • Use querySelector for flexible DOM access
  • Always check for null before manipulating elements
  • Use requestAnimationFrame() for smooth animations
  • Avoid inline event handlers; use addEventListener

Summary

You now understand how to:

  • Access and manipulate DOM elements
  • Handle form inputs and validations
  • Animate with setInterval() or requestAnimationFrame()
  • Navigate the DOM tree effectively

Mastering the DOM is essential for dynamic, interactive web applications. Itโ€™s the heart of client-side JavaScript development.


FAQ Section

What is the DOM in JavaScript?

The DOM is a tree-like structure representing HTML elements as JavaScript objects. It lets you dynamically read and manipulate web content.

What is the difference between innerHTML and textContent?

  • innerHTML: Parses and sets HTML content (can introduce security risks).
  • textContent: Only sets or gets plain text.

How can I change the style of a DOM element?

document.getElementById("box").style.color = "red";

Directly manipulates CSS styles using .style.property.

What is requestAnimationFrame() used for?

It is a browser API that schedules smooth animations, synced with screen refresh rates for better performance than setInterval().

How to validate forms using the DOM?

Use JavaScript to check input values before form submission, often with addEventListener('submit', callback) and input .value.


Share Now :
Share

JavaScript โ€” DOM (Elements, Forms, Animations, Navigation)

Or Copy Link

CONTENTS
Scroll to Top