Javascript Deep Dive Series

7 min read
📝 1021 words
Javascript Deep Dive Series

This series will help you understand Javascript in depth. Javascript Tutorial Series :

  • ES6 Features
  • ES7 Features
  • ES8 Features
  • ES9 Features
  • ES10 Features

Concepts

  • Dom Traversal and Manipulation
  • var, let and const
  • Hoisting
  • Temporal Dead Zone (TDZ)
  • Template Literals
  • Arrow Functions
  • Default Parameters
  • Enhanced object literals
  • Sets and Weaksets
  • Maps and WeakMaps
  • Rest and Spread Operator (…)
  • Array and Object Destructuring
  • Classes
  • Promises
  • Modules

Question Banks :

Ebook Repos:

DOM Traversal and Manipulation using Javascript

Before DOM manipulation, it's important to understand How to traverse the DOM

Traversing the DOM in JS

Traversing and manipulating the DOM (Document Object Model) without using any JavaScript frameworks or libraries like Angular or React involves working directly with the native DOM API. This can be done using HTML, CSS, and vanilla JavaScript. Here's a detailed guide on how to traverse and manipulate the DOM using various event listeners and DOM manipulation methods:

  1. Basic DOM Traversal:

To start, you need to understand how to access elements in the DOM and traverse through their structure.

  • getElementById: Retrieve an element by its unique ID.
<div id="myElement"></<em>div</em>>

// javascript
const element = document.getElementById("myElement");
  • getElementsByClassName: - Retrieve a collection of elements with the same class name.
<div class="myClass"></div>
<div class="myClass"></div>

// javascript
const elements = document.getElementsByClassName("myClass");

  • getElementsByTagName: Retrieve a collection of elements with the same tag name.
<div></div>
<div></div>
// javascript
const elements = document.getElementsByTagName("div");
<<em>p</em>></<em>p</em>>
 <<em>p</em>></<em>p</em>>

// javascript
const paragraphs = document.getElementsByTagName(“p”);
  • querySelector: - Retrieve the first element that matches a given CSS selector.
const element = document.querySelector(.myClass”);
  • querySelectorAll: - Retrieve a collection of elements that match a given CSS selector.
const elements = document.querySelectorAll(.myClass”);
  1. Traversing the DOM Tree: Once you have access to an element, you can traverse its relationships with other elements in the DOM tree.
  • parentNode: Access the parent element of a given element.
const parent = element.parentNode;
  • childNodes: Access the child nodes of a given element.
const children = element.childNodes;
  • firstChild: Access the first child node of a given element.
const firstChild = element.firstChild;
  • lastChild: Access the last child node of a given element.
const lastChild = element.lastChild;
  • nextSibling: Access the next sibling node of a given element.
const nextSibling = element.nextSibling;
  • previousSibling: Access the previous sibling node of a given element.
const previousSibling = element.previousSibling;
  1. Manipulating the DOM:

DOM manipulation involves modifying elements, attributes, and content.

// Change the text content of an element
element.textContent = "New text content";

// Change the HTML content of an element
element.innerHTML = "<span>New HTML content</span>";

// Change the style of an element
element.style.color = "red";

// Add a class to an element
element.classList.add("new-class");

// Remove a class from an element
element.classList.remove("old-class");

// Create a new element
const newElement = document.createElement("div");
newElement.textContent = "Hello, World!";

// Append a new element to the DOM
document.body.appendChild(newElement);

// Remove an element from the DOM
document.body.removeChild(element);
  1. Creating Elements and Appending to the DOM:
const newElement = document.createElement("div");
newElement.textContent = "Hello, World!";
document.body.appendChild(newElement);
  1. Appending and Inserting Elements:
const parent = document.getElementById("parent");
const newElement = document.createElement("div");
newElement.textContent = "New Child Element";
parent.appendChild(newElement); // Append as the last child
parent.insertBefore(newElement, parent.firstChild); // Insert as the first child
  1. Updating Attributes:
const element = document.getElementById("myElement");
element.setAttribute("data-custom", "value"); // Set a custom attribute
const attrValue = element.getAttribute("data-custom"); // Get the attribute value
element.removeAttribute("data-custom"); // Remove the attribute

If you want to change the class of an element:

element.setAttribute("class", "newClass");
  1. Changing Content:
element.textContent = “New text content”;
element.innerHTML =<p>New HTML content</p>;
  1. Removing Elements:
const element = document.getElementById("myElement");
element.parentNode.removeChild(element); // Remove the element from the DOM

Common DOM Events and Event Listeners:

Here are a few common DOM events you might encounter:

  • click: Triggered when an element is clicked.
  • submit: Triggered when a form is submitted.
  • keydown/keyup: Triggered when a keyboard key is pressed/released.
  • mouseover/mouseout: Triggered when the mouse pointer enters/leaves an element.
  • change: Triggered when the value of an input element changes.
Check if document has loaded

So there are multiple ways to check if the document is loaded

  1. readyStateChange

The Document.readyState property describes the loading state of the document . When the value of this property changes, a readystatechange event fires on the document object.

document.onreadystatechange = function () {
    if (document.readyState === "complete") {
        // Document is fully loaded
    }
};

document.onreadystatechange = () => {
  if (document.readyState == "loading") {
    console.log("loading...");
  }
  if (document.readyState == "interactive") {
    console.log("interactive...");
  }
  if (document.readyState == "complete") {
    console.log("complete...");
    // init app
  }
};
// using event handler
document.addEventListener(“readyStateChange”, (<em>event</em>) => {
    if (event.target.readyState == 'loading') {
      console.log('document is loading...')
    }
    if (event.target.readyState == 'interactive') {
    initLoader();
  } else if (event.target.readyState === "complete") {
        console.log('page loaded')
      initApp();
     }
}
  1. DOMContentLoaded event

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

document.addEventListener("DOMContentLoaded", function() {
    // Document is fully loaded
});
  1. window.onload event

The load event is fired when the whole page has loaded, including all dependent resources such as styles heets and images.

window.onload = function() {
    // Document and all resources are fully loaded
};
window.addEventListener("load", (<em>event</em>) => {
  console.log("page loaded");
});

//or

window.onload = function () {
 console.log('page is loaded...'
}