Ever wondered how your favourite websites come to life? It's all thanks to DOM manipulation!
If you're a web developer, the DOM (Document Object Model) is your canvas, and today we're going to paint a masterpiece!
DOM
In the context of web development and HTML (Hypertext Markup Language), a "DOM" stands for Document Object Model.
The Document Object Model is a programming interface used to represent and interact with structured documents like HTML and XML.
It is a programming interface that provides a structured representation of a web page's elements, enabling developers to manipulate and interact with the document using scripting languages like JavaScript.
The DOM is a critical part of web development, and the DOM API is a significant component of the JavaScript API when it comes to web document manipulation.
Through this, we'll be able to change a lot of stuff in your HTML structure.
Dom is an API by js to do some query on your HTML document structure and lets us do certain manipulations like setting new values and stuff.
DOM is the tree representation of HTML elements, in which HTML is the root node of it.
JS DOM API going to traverse the DOM tree, to retrieve any of the information and change that.
DOM manipulation
Quering DOM:
- Selecting Elements: You can use various methods like
getElementById
,getElementsByClassName
,getElementsByTagName
, orquerySelector
to select HTML elements within the DOM.
- Selecting Elements: You can use various methods like
const elementById = document.getElementById("myElement");
const elementsByClass = document.getElementsByClassName("myClass");
const elementsByTag = document.getElementsByTagName("div");
const elementBySelector = document.querySelector(".mySelector");
- Traversing: You can navigate through the DOM tree by accessing parent, child, or sibling elements.
const parentElement = childElement.parentNode;
const firstChild = parentElement.firstChild;
const nextSibling = firstChild.nextSibling;
Updating DOM:
- Modifying Content: You can change the content of HTML elements, such as text, attributes, or inner HTML.
const element = document.getElementById("myElement");
element.textContent = "New Text";
element.setAttribute("src", "new-image.jpg");
element.innerHTML = "<p>New HTML Content</p>";
- Creating Elements: You can create new elements and append them to the DOM.
const newElement = document.createElement("div");
newElement.textContent = "Newly Created Element";
document.body.appendChild(newElement);
- Removing Elements: You can remove elements from the DOM.
const elementToRemove = document.getElementById("elementToRemove");
elementToRemove.parentNode.removeChild(elementToRemove);
DOM Rendering:
Reflow and Repaint: When you manipulate the DOM, it can trigger a reflow (recalculating the layout) and repaint (applying the visual changes) of the affected elements, which can impact performance. Minimizing unnecessary DOM changes is essential for efficient rendering.
Event Handling: You can attach event listeners to DOM elements to respond to user interactions, like clicks or input changes.
const button = document.getElementById("myButton");
button.addEventListener("click", () => {
// Handle click event
});
Moving from DOM to Virtual DOM
If we want to refresh more often, then the performance of the site will be reduced. Here the Libraries and the framework came into pic to resolve the issue like React.
React's declarative nature suggests that, we don't have to update the DOM at any point of time. Generally we don't directly manipulate DOM in react.
React automatically updates the DOM to match your render output, so your components won’t often need to manipulate it.
However, sometimes you might need access to the DOM elements managed by React—for example, to focus a node, scroll to it, or measure its size and position. There is no built-in way to do those things in React, so you will need a ref to the DOM node.
To access a DOM node managed by React we use the useRef()
hook.
import { useRef } from 'react';
const myRef = useRef(null);
//Finally, pass your ref as the ref attribute to the JSX tag
//for which you want to get the DOM node
<div ref={myRef}>
React never update the dom tree directly, React creates for every dom tree representation one object called Virtual dom. That looks exactly like DOM tree. That particular copy of the original dom is called a virtual dom
The useRef
Hook returns an object with a single property called current
. Initially, myRef.current
will be null
. When React creates a DOM node for this <div>
, React will put a reference to this node into myRef.current
. You can then access this DOM node from your event handlers and use the built-in browser APIs defined on it.
myRef.current.scrollIntoView();
Virtual DOM (VDOM)
It is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called Reconciliation.
The virtual dom is an in-memory object that React
keeps updating, and any in-memory operations are faster.
React creates the dom structure in-memory copy of the element. In the virtual DOM each node represents an element.
If the one element of the dom got updated then the react makes the copy of the existing virtual dom, with the element and their child element updated.
Then there is an algorithm called BATCH UPDATE, and react takes the call when is the right time to do this BATCH update the original dom, there might be another state change happen.
According to the right time, based on the algorithm, the react updates the original dom by the BATCH UPDATE.
The advantage of it is that we don't have to traverse the whole dom tree to change the particular element. All things are taken care of by React
By the use of DIFFING ALGO algorithm the react checks the element that's changed by comparing to the original dom with the in-memory copy of the virtual dom.
If the root itself got changed, then by the DIFFING algorithm it destroys that root and their child element and then makes another one, that is changed one
Here in the above no tear down happened only the attribute section "className" got changed and only that particular portion will be reflected or changed as per the batch update of the original DOM.
Key
When there's a list and, a list has to be compared, React takes both of them in the memory and does a line-by-line comparison. This kind of comparison is a little bit heavier, and with more li
elements is there. it'll affect your performance. That's when we use the special element called KEY.
In react when we are listing the element and if we don't use the key, then the whole list will get updated, but we don't want that, do we?
Using the key React checks which element is updated, so whenever we do the listing, use the key. It'll improve the performance of the react application.
Thanks for reading this blog.
Check out my Portfolio website Click me.
Please give likes, if you like this blog.