Skip to main content

Command Palette

Search for a command to run...

What is DOM manipulation in JavaScript?

Updated
2 min read
What is DOM manipulation in JavaScript?
M

I’m a Front End web developer. Everyone likes to write. I’m one of them. However, I’m not a professional writer. Sometimes I write and publish my experiences.

What is DOM Manipulation?

DOM stands for Document Object Model.
Structured representation of HTML documents allows JavaScript to access HTML elements and styles to manipulate them!

  • Change text, HTML attributes, and even CSS styles.
  • Access HTML elements.

DOM Tree

A special object is the entry point to the DOM.
Example:

document.qureySelector();

dom.jpg

Selecting Elements

In order to be able to manipulate an element in the DOM, you have to select that particular element. Lucky for us we have four major ways of selecting elements.

  • getElementById()
  • querySelector()
  • getElementByClassName()
  • getElementsByTagName()

Example:

<div class="blog" id="blogPost">Something here...</div>
// getElementById()
const post = document.getElementById("blogPost");

// querySelector()
// Selecting a Class
document.querySelector(".blog");

// Selecting an Id
document.querySelector("#blogPost");

Changing HTML Elements

Property

element.innerHTML = new HTML content

document.getElementById("heading1").innerHTML = "This heading will change";

element.style.property = new style

document.querySelector(".container").style.backgroundColor = "blue";

Add / Remove Class

Adding class

element.querySelector.classList.add("class name")

// CSS
.hidden {
display: none;
}
// JavaScript
document.querySelector(".container").classList.add("hidden");

Removing class

element.querySelector.classList.remove("class name")

// CSS
.hidden {
display: none;
}
// JavaScript
document.querySelector(".container").classList.remove(".hidden");

Events and Event Handlers

Events are actions that happen when the user or browser manipulates a page.
If a user clicks a button on a page, then a click event has happened.

addEventListener()
target.addEventListener(event, function)

Here, target means HTML element

The most common events you might "listen out for" are

  • load
  • click
  • mouseout
  • mouseover.