🌐 JavaScript DOM & Browser BOM
Estimated reading: 4 minutes 10 views

🧩 JavaScript — DOM Methods & Properties: A Complete Guide with Examples


🧲 Introduction – Why DOM Methods & Properties Are Crucial

If you’ve ever interacted with an HTML element using JavaScript—clicked a button, updated text, or added a new element—you’ve used DOM methods and properties.

The Document Object Model (DOM) enables JavaScript to dynamically manipulate HTML and CSS. Mastering its methods and properties is essential for creating responsive and interactive web applications.

By the end of this guide, you’ll be able to:

  • ✅ Access, modify, and delete DOM elements
  • ✅ Use essential DOM methods and properties
  • ✅ Traverse and manipulate the DOM tree
  • ✅ Work with attributes, classes, and element structures

🧱 1. DOM Properties – Accessing Element Data

DOM properties allow you to get or set data on an element.

✅ Common DOM Properties:

PropertyDescription
innerHTMLGet/set HTML content inside an element
textContentGet/set plain text inside an element
valueGet/set value for input, textarea, select
styleAccess inline styles (e.g., el.style.color)
classNameRead/write class attribute as a string
idGet/set the element’s ID
tagNameReturns the tag name of an element
childrenReturns a collection of child elements

🔍 Example: Accessing & Changing Properties

<p id="message">Hello World</p>
const el = document.getElementById("message");
console.log(el.textContent);       // Hello World
el.textContent = "Updated!";       // ✅ Changes text
el.style.color = "red";            // ✅ Changes text color

📘 Use textContent for plain text, and innerHTML if you need HTML formatting.


🔧 2. DOM Methods – Modify the Page Dynamically

DOM methods let you create, append, remove, and find elements programmatically.

✅ Essential DOM Methods:

MethodDescription
getElementById(id)Selects one element by ID
getElementsByClassName(class)Selects elements by class name
getElementsByTagName(tag)Selects elements by tag
querySelector(selector)Selects first match using CSS selector
querySelectorAll(selector)Selects all matches using CSS selector
createElement(tag)Creates a new element
appendChild(node)Appends a child element
removeChild(node)Removes a child element
replaceChild(new, old)Replaces one child with another
setAttribute(attr, val)Sets a custom attribute
getAttribute(attr)Gets the value of an attribute
classList.add() / remove()Modify class names dynamically

✏️ Example: Create and Insert Element

const newEl = document.createElement("div");
newEl.textContent = "I was added!";
document.body.appendChild(newEl);

✅ Adds a new <div> with text to the end of <body>.


✂️ Example: Remove Element

const oldEl = document.getElementById("removeMe");
oldEl.remove(); // Modern method

✅ Removes the element from the DOM immediately.


🧭 3. DOM Traversal – Navigating the DOM Tree

DOM traversal allows you to navigate between related elements.

🔁 Traversal Properties:

PropertyDescription
parentNodeGets the parent element
childNodesAll child nodes (including text)
childrenElement-only children
firstElementChildFirst child that is an element
lastElementChildLast child element
nextElementSiblingNext sibling element
previousElementSiblingPrevious sibling element

🔍 Example: Navigate and Change Parent’s Style

let child = document.querySelector(".child");
child.parentNode.style.background = "yellow";

✅ Applies style to the parent of the .child element.


🎨 4. Working with Classes and Attributes

🎯 classList API

element.classList.add("active");
element.classList.remove("hidden");
element.classList.toggle("open");
element.classList.contains("selected"); // returns true/false

✅ Easily manage CSS classes dynamically.


🔐 Attributes

const el = document.querySelector("a");
el.setAttribute("target", "_blank");
let href = el.getAttribute("href");

✅ Read or modify any HTML attribute from JavaScript.


🧪 Real-World Example – Create a List from Array

const items = ["HTML", "CSS", "JavaScript"];
const ul = document.createElement("ul");

items.forEach(text => {
  let li = document.createElement("li");
  li.textContent = text;
  ul.appendChild(li);
});

document.body.appendChild(ul);

✅ Dynamically generates a list using DOM methods.


💡 Best Practices

  • ✅ Use querySelector for flexible and modern element access
  • 🧠 Always check if an element exists before manipulating it
  • 🚫 Avoid excessive use of innerHTML for security (XSS risk)
  • 🧼 Remove unused elements to prevent memory leaks

📌 Summary

Let’s recap what you’ve learned:

✅ DOM properties help you read or update content and attributes
✅ DOM methods let you create, remove, find, and insert elements
✅ DOM traversal allows you to navigate parent-child-sibling relationships
classList and setAttribute simplify style and data manipulation

Mastering these tools makes your JavaScript code powerful, interactive, and ready for modern web applications.


❓ FAQs

❓ What’s the difference between innerHTML and textContent?

  • innerHTML: Renders HTML tags (unsafe for user input)
  • textContent: Only displays raw text (safe for user input)

❓ What is querySelector() vs getElementById()?

  • querySelector() is more flexible and uses CSS selectors
  • getElementById() is faster and simpler for known IDs

❓ How can I create a new HTML element using JavaScript?

Use document.createElement(tagName) and then append it:

let p = document.createElement("p");
p.textContent = "New paragraph";
document.body.appendChild(p);

❓ What is classList used for?

classList is a DOM property that allows you to add, remove, toggle, and check CSS classes dynamically.


❓ Is removeChild() still used?

Yes, but modern JavaScript supports element.remove() which is more concise and readable.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

JavaScript — DOM Methods & Properties

Or Copy Link

CONTENTS
Scroll to Top