#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
DOM & Validation

Understanding DOM and BOM

What is the DOM?

The Document Object Model (DOM) is a tree-like representation of an HTML page that JavaScript can use to access and manipulate elements, attributes, and content.

document.getElementById("title").innerText = "New Title";
document.querySelector(".box").style.color = "red";

What is the BOM?

The Browser Object Model (BOM) allows JavaScript to interact with the browser itself, outside the page content — things like the window, navigation history, and screen.

Common BOM Objects

  • window — the global browser window object.
  • navigator — information about the browser.
  • location — the current URL, allows redirection.
  • history — the browser's session history.
  • screen — information about the user's screen.

DOM vs BOM

The DOM deals with the content of the web page, while the BOM deals with the browser window surrounding that page.

Walking and Changing the DOM Tree

Every tag in the page becomes a node, and nodes have parents, children and siblings. You can move around the tree and build new elements:

const list = document.querySelector("#tasks");

console.log(list.children.length);       // number of li elements
console.log(list.firstElementChild);     // the first li
console.log(list.parentElement);         // the element that contains the list

const item = document.createElement("li");
item.textContent = "Review pull request";
item.classList.add("pending");
list.append(item);

list.firstElementChild.remove();

Use textContent when inserting text typed by a user. Setting innerHTML with user input can let unwanted HTML or scripts into the page, which is a common security hole known as cross-site scripting.

It also helps to know what the selection methods return. getElementById and querySelector give back a single element, or null when nothing matches, so check the result before using it. querySelectorAll returns a static list captured at that moment, while getElementsByClassName returns a live collection that updates itself as the page changes. Attributes can be read and changed with getAttribute and setAttribute, and custom data- attributes are available through the dataset property.

Worked Example: A Simple To-Do List

<input id="taskInput" placeholder="New task">
<button id="addBtn">Add</button>
<ul id="tasks"></ul>

<script>
  const input = document.getElementById("taskInput");
  const tasks = document.getElementById("tasks");

  document.getElementById("addBtn").addEventListener("click", () => {
    const text = input.value.trim();
    if (!text) return;
    const li = document.createElement("li");
    li.textContent = text;
    tasks.append(li);
    input.value = "";
  });

  // one listener on the parent handles clicks on every li (event delegation)
  tasks.addEventListener("click", (event) => {
    if (event.target.tagName === "LI") {
      event.target.classList.toggle("done");
    }
  });
</script>

Event delegation means you do not need to attach a new listener each time a task is added, which keeps code shorter and memory use lower. It works because most events bubble: a click on an li travels up to the ul, where the single listener checks event.target to see which item was actually clicked.

Notice the early return when the input is empty. Small guards like this stop blank items from appearing and are a habit worth building from your first DOM script.

Practical BOM Examples

console.log(window.innerWidth, window.innerHeight);  // viewport size
console.log(location.href, location.pathname);       // current address
console.log(navigator.language);                    // preferred language

location.assign("/dashboard");     // go to a new page, keeps history
history.back();                    // same as the browser Back button

const timer = setTimeout(() => console.log("2 seconds later"), 2000);
clearTimeout(timer);               // cancel it

localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme"));

Because window is the global object in browsers, window.setTimeout and setTimeout are the same thing. Strictly speaking, document itself is also a property of window, which is how the DOM and BOM connect.

Common Mistakes

  • Running scripts before the elements exist. Place scripts at the end of the body, add the defer attribute, or wait for the DOMContentLoaded event.
  • Updating the DOM inside large loops. Build items in a DocumentFragment and append once to reduce reflows.
  • Confusing node lists with arrays. querySelectorAll returns a NodeList; use Array.from() if you need methods like map.
  • Relying on navigator.userAgent to detect features. Test for the feature directly instead.
  • Using alert for normal messages; it blocks the page and annoys users. Show messages in the page instead.

Ready to master real-world JavaScript development?

Learn JavaScript hands-on with mentor-led, live sessions.

Explore Course