Skip to main content

DOM Manipulation

The Document Object Model (DOM) is the browser’s representation of your HTML. JavaScript provides powerful APIs to manipulate the DOM and create dynamic, interactive web pages.

Show and Hide Elements

JavaScript allows you to change the CSS properties of an element by accessing its style property. This way, you can show or hide HTML elements by changing their display property.

Hide Elements

In order to hide an HTML element, you can use the display: none CSS property. This will remove the element from the page layout, but it will still be present in the DOM.

Show Elements

Most HTML elements have a default display property value. For example, the default value for <div> elements is block, while the default value for <span> elements is inline. In order to show an element, you can set its display property to its default value, or to an empty string ('').
Combining the spread operator (...) with Array.prototype.forEach() allows you to show or hide multiple elements at once.

Rendering DOM Elements

Have you ever wondered how React’s rendering works under the hood? Here’s a simple JavaScript function that renders a DOM tree in a specified container.

Representing a DOM Tree

Each element is an object with a type property representing the element’s tag name, and a props object containing the element’s attributes, event listeners, and children.
The special case of text elements is represented by an object without a type property, only containing a props object with a nodeValue property.

Render Function

This implementation is for demonstration purposes only and lacks many features and optimizations present in React or Preact.

Creating Elements

createElement

createTextNode

Modifying Elements

Text Content

Use textContent for plain text and innerHTML for HTML. Be careful with innerHTML when dealing with user input to prevent XSS attacks.

Attributes

Classes

Styles

Removing Elements

Inserting Elements

appendChild

insertBefore

insertAdjacentHTML

Cloning Elements

Best Practices

DOM manipulation is expensive. Batch changes together and use DocumentFragment for multiple insertions.
classList provides methods like add, remove, toggle, and contains, making it easier and more reliable than manipulating className string.
When using innerHTML with user input, always sanitize the content to prevent XSS attacks. Consider using textContent instead.
If you need to access an element multiple times, cache the reference instead of querying the DOM repeatedly.