Sitemap
Mighty ghost hack

A passionate full-stack developer, Ethical Hacker, Blogger, Youtuber and many more

Javascript DOM Manipulation methods

3 min readOct 25, 2024

--

Press enter or click to view image in full size
A graphical representation of the HTML DOM tree

What is the DOM?

DOM stands for Document Object Model.

The Document part refers to the webpage you see in the browser—specifically, the HTML Document.

Object means the elements like images, headers, and paragraphs are treated like objects. Each object has its properties (like id, class, style) and methods. Using these properties and methods, you can manipulate the elements.

The Model in DOM is a representation of the HTML document as a hierarchical tree. This tree includes all the elements. And it captures the parent-child relationships between them.

DOM Manipulation

  1. Selecting Elements
  2. Creating Elements
  3. Adding or Inserting Elements
  4. Removing Elements
  5. Modifying Element Content
  6. Modifying Attributes
  7. Modifying Styles
  8. Traversing the DOM
  9. Event Handling
  10. Other Useful DOM Utility Methods

1. Selecting Elements

These methods allow you to select elements from the DOM:

document.getElementById(id): Select an element by its id.

const element = document.getElementById('myId');

document.getElementsByClassName(className): Select all elements with the specified class.

const elements = document.getElementsByClassName('myClass');

document.getElementsByTagName(tagName): Selects all elements with the specified tag name.

const elements = document.getElementsByTagName('div');

document.querySelector(selector): Select the first element that matches a CSS selector.

const element = document.querySelector('.myClass');

document.querySelectorAll(selector): Select all elements that match a CSS selector.

const elements = document.querySelectorAll('.myClass');

2. Creating Elements

These methods create new elements or text nodes:

document.createElement(tagName): Creates a new element with the specified tag name.

const newDiv = document.createElement('div');

document.createTextNode(text): Creates a new text node with the specified text.

const textNode = document.createTextNode('Hello World');

3. Adding or Inserting Elements

These methods add new elements to the DOM or insert elements at specific positions:

parentNode.appendChild(childNode): Adds childNode as the last child of parentNode.

document.body.appendChild(newDiv);

parentNode.insertBefore(newNode, referenceNode): Inserts newNode before referenceNode within parentNode.

const referenceNode = document.getElementById('myId');
document.body.insertBefore(newDiv, referenceNode);

parentNode.prepend(newNode): Inserts newNode as the first child of parentNode.

document.body.prepend(newDiv);

element.insertAdjacentElement(position, newElement): Inserts an element relative to another element. Positions include beforebegin, afterbegin, beforeend, and afterend.

element.insertAdjacentElement('beforeend', newDiv);

4. Removing Elements

These methods remove elements or child nodes:

parentNode.removeChild(childNode): Removes childNode from parentNode.

document.body.removeChild(newDiv);

element.remove(): Removes element from the DOM directly.

newDiv.remove();

5. Modifying Element Content

These properties and methods modify the content inside elements:

Get Mayur Kadam’s stories in your inbox

Join Medium for free to get updates from this writer.

element.textContent: Gets or sets the text content of an element.

element.textContent = 'Hello, World!';

element.innerHTML: Gets or sets the HTML content of an element.

element.innerHTML = '<strong>Hello, World!</strong>';

element.outerHTML: Gets or replaces the element itself with new HTML content.

element.outerHTML = '<div>New Content</div>';

6. Modifying Attributes

These methods manage element attributes:

element.getAttribute(attributeName): Gets the value of an attribute.

const id = element.getAttribute('id');

element.setAttribute(attributeName, value): Sets the value of an attribute.

element.setAttribute('class', 'newClass');

element.removeAttribute(attributeName): Removes an attribute.

element.removeAttribute('class');

element.hasAttribute(attributeName): Checks if an attribute exists.

const hasId = element.hasAttribute('id');

7. Modifying Styles

These methods modify inline styles:

element.style.property: Sets an inline style property.

element.style.color = 'red';

element.classList.add(className): Adds a class to the element.

element.classList.add('myClass');

element.classList.remove(className): Removes a class from the element.

element.classList.remove('myClass');

element.classList.toggle(className): Toggles a class on or off.

element.classList.toggle('active');

element.classList.contains(className): Checks if an element contains a specified class.

const hasClass = element.classList.contains('active');

8. Traversing the DOM

These properties and methods navigate through the DOM tree:

element.parentNode: Gets the parent of an element.

const parent = element.parentNode;

element.childNodes: Gets a list of an element's child nodes.

const children = element.childNodes;

element.firstChild: Gets the first child of an element.

const firstChild = element.firstChild;

element.lastChild: Gets the last child of an element.

const lastChild = element.lastChild;

element.previousSibling: Gets the previous sibling of an element.

const prevSibling = element.previousSibling;

element.nextSibling: Gets the next sibling of an element.

const nextSibling = element.nextSibling;

element.children: Returns an HTMLCollection of child elements.

const childElements = element.children;

element.firstElementChild and element.lastElementChild: Access the first and last child elements.

const firstElement = element.firstElementChild;

9. Event Handling

These methods attach and remove event listeners:

element.addEventListener(event, handler): Attaches an event listener to an element.

element.addEventListener('click', () => console.log('Clicked!'));

element.removeEventListener(event, handler): Removes an event listener from an element.

element.removeEventListener('click', handler);
// OR
const listener = element.addEventListener('click', handler);
element.removeEventListener(listener);

10. Other Useful DOM Utility Methods

element.cloneNode(deep): Creates a clone of an element. Pass true to also clone child elements.

const clone = element.cloneNode(true);

element.contains(childNode): Checks if an element contains a specific child node.

const isContained = element.contains(childNode);

element.replaceChild(newChild, oldChild): Replace an existing child with a new one.

element.replaceChild(newNode, oldNode);

These methods give you comprehensive control over the DOM, allowing you to select, create, manipulate, traverse, and delete elements dynamically, as well as handle events. This is essential for building interactive, dynamic web applications.

--

--