DOM (Document Object Model)

Decoding The Heartbeat of the Web

DOM (Document Object Model)

Definition of DOM

The Document Object Model is like the blueprint of a web page. It's a structured representation of the HTML elements that make up a website. Imagine it as a family tree, with each element being a family member—some are parents, some are kids, and they all live together in harmony!

Document Object

Using the Document Object, developers can access and modify the content, structure, and style of the entire web page. It serves as the entry point to the DOM, allowing for tasks such as selecting elements, creating new elements, or even altering the page's structure dynamically using JavaScript.

getElementById

This method selects an element by its unique id attribute.

//HTML code <div id="uniqueId">I'm unique!</div>
const elementById = document.getElementById('uniqueId')

getElementsByClassName

It selects elements by their shared class name. It returns a collection (array-like) of elements.

// HTML
// <p class="myClass">First paragraph</p>
// <p class="myClass">Second paragraph</p>
const elementsByClass = document.getElementsByClassName('myClass')

querySelector

This method uses CSS selector syntax to select the first matching element.

// HTML
// <div class="container">
//    <p id="text">Hello, World!</p>
// </div>

const querySelector = document.querySelector('.container #text');

querySelectorAll

Similar to querySelector, but returns a collection of all matching elements.

// HTML
// <ul>
//   <li>Item 1</li>
//   <li>Item 2</li>
//   <li>Item 3</li>
// </ul>

const querySelectorAll = document.querySelectorAll('ul li')

Key Differences

  • getElementById is singular and unique, while getElementsByClassName, querySelector, and querySelectorAll can target multiple elements.

  • getElementById directly returns the specific element, while the others return a collection.

  • querySelector and querySelectorAll utilizes CSS selector syntax, providing more flexibility in selection.

Some common methods used in DOM Manipulation

classList

This method deals with the classes of an element, allowing you to add, remove, or toggle classes.

// HTML
// <div id="myElement" class="box">Hello</div>
const element = document.getElementById('myElement')

// Adding a class inside a Element or Tag
element.classList.add('highlight')

// Removing a class
element.classList.remove('box')

// Toggling a class
element.classList.toggle('underline')

append

This method allows you to add HTML elements or text to the end of an element's content.

// HTML
// <div id="myDiv">Hello</div>

const div = document.getElementById('myDiv');

const paragraph = document.createElement('p');
paragraph.textContent = 'How are you?';

div.append(paragraph)

remove

The remove method removes an element from the DOM.

// HTML
// <div id="parent">
//    <p>Hello</p>
// </div>

const parent = document.getElementById('parent');
const child = parent.querySelector('p');

child.remove();

innerHTML and innerText

These properties deal with the content within an element.

innerHTML sets or returns the HTML content within an element, including HTML tags.

// HTML
// <div id="myElement">Hello</div>

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

element.innerHTML = '<p>New content with <strong>HTML</strong> tags</p>';

innerText sets or returns the text content of the specified element, without HTML tags.

// HTML
// <div id="myElement">Hello <strong>World</strong></div>

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

const text = element.innerText;
console.log(text); // Outputs: "Hello World"

Traversal in DOM

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>DOM Traversal</title>
        <style>
            div{
                color: black;
            }
            div > div{
                margin-left: .5rem;
                padding-left: .25rem;
                border-left: 1px solid #777;
            }
        </style>
        <script src="dom-traversal.js" defer></script>
    </head>
    <body>
        <div class="grand-parent">
            Grand Parent
            <div>Parent 1
                <div class="child-one">Child 1</div>
                <div>Child 2</div>
            </div>
            <div>Parent 2</div>
        </div>
    </body>
</html>
  1. Selecting Child Elements using Parent and color them

const grandpa = document.querySelector(".grand-parent")

//Selecting from grandpa to child elements
grandpa.style.color = "red"

const parent1 = grandpa.children[0]

console.log(parent1)
parent1.style.color = "green"

const parent2 = parent1.nextElementSibling
// similarly we can use previousElementSibling or previousSibling or nextSibling
parent2.style.color = "blue"

parent1.children[1].style.color = "purple"
  1. Selecting Parent Elements using Child and color them

//--------------- Selecting from child elements to Grandpa

const child1 = document.querySelector(".child-one")
child1.style.color = "red"

const parent1 = child1.parentElement

parent1.style.color = "green"
parent1.nextElementSibling.style.color = "darkgreen"

const grandpa = child1.closest(".grand-parent") 
//it select the closest parent
grandpa.style.color = "red"

Mini project Based on Above Learning

  1. Basic Todo List using DOM Manipulation

  2. Basic Toggle of Modal and Overlay

Comment if I have committed any mistake. Let's connect on my socials. I am always open to new opportunities if I am free :P

Linkedin| Twitter | ShowwCase