DEV Community

Cover image for Web Dev Day 7: JavaScript Guide Part 2
Bhupesh Kumar
Bhupesh Kumar

Posted on

Web Dev Day 7: JavaScript Guide Part 2

What is the DOM in JavaScript?

The Document Object Model (DOM) is a programming interface that allows JavaScript to interact with, manipulate, and update web pages dynamically.

It represents an HTML document as a tree structure, where each HTML element is a node.

1. Understanding the DOM Structure

Consider this HTML document:

<!DOCTYPE html>
<html>
<head>
    <title>DOM Example</title>
</head>
<body>
    <h1 id="heading">Hello, DOM!</h1>
    <p class="text">This is a paragraph.</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

How the DOM Represents This Page:

Document
 ├── html
 │    ├── head
 │    │    ├── title
 │    ├── body
 │         ├── h1 (id="heading")
 │         ├── p (class="text")
Enter fullscreen mode Exit fullscreen mode

2. Accessing the DOM Using JavaScript

Selecting Elements by ID (getElementById)

let heading = document.getElementById("heading");
console.log(heading.textContent);  
// Output: "Hello, DOM!"
Enter fullscreen mode Exit fullscreen mode

Selecting Elements by Class (getElementsByClassName

let paragraphs = document.getElementsByClassName("text");
console.log(paragraphs[0].textContent);  
// Output: "This is a paragraph."
Enter fullscreen mode Exit fullscreen mode

Selecting Elements by Tag Name (getElementsByTagName)

let allHeadings = document.getElementsByTagName("h1");
console.log(allHeadings[0].textContent);  
// Output: "Hello, DOM!"
Enter fullscreen mode Exit fullscreen mode

Modern Way: Using querySelector and querySelectorAll

let heading = document.querySelector("#heading"); // Selects by ID
let paragraph = document.querySelector(".text"); // Selects first element with class
let allParagraphs = document.querySelectorAll(".text"); // Selects all elements with class

console.log(heading.textContent);  
// Output: "Hello, DOM!"
Enter fullscreen mode Exit fullscreen mode

3. Modifying the DOM (Changing Content)

Changing Inner HTML

document.getElementById("heading").innerHTML = "<span style='color:red'>Hello, JS!</span>";
Enter fullscreen mode Exit fullscreen mode

Changing Text Content

document.getElementById("heading").textContent = "Hello, JavaScript!";
Enter fullscreen mode Exit fullscreen mode

4. Manipulating DOM Elements

Adding a New Element (createElement & appendChild)

let newPara = document.createElement("p");
newPara.textContent = "This is a new paragraph!";
document.body.appendChild(newPara);
Enter fullscreen mode Exit fullscreen mode

Removing an Element (removeChild)

let element = document.getElementById("heading");
element.parentNode.removeChild(element);
Enter fullscreen mode Exit fullscreen mode

Changing CSS Styles Using JavaScript

document.getElementById("heading").style.color = "blue";
Enter fullscreen mode Exit fullscreen mode

5. Handling Events in the DOM

Adding an Event Listener

document.getElementById("heading").addEventListener("click", function() {
    alert("Heading clicked!");
});
Enter fullscreen mode Exit fullscreen mode

Removing an Event Listener

function greet() {
    console.log("Heading clicked!");
}

let heading = document.getElementById("heading");
heading.addEventListener("click", greet);
heading.removeEventListener("click", greet);
Enter fullscreen mode Exit fullscreen mode

Manipulating Attributes in JavaScript (DOM)

JavaScript provides methods to add, modify, and remove attributes of HTML elements dynamically.

1. Accessing Attributes

getAttribute()

Gets the value of an attribute.

let link = document.querySelector("a");
console.log(link.getAttribute("href"));  
// Output: The URL inside the `href` attribute
Enter fullscreen mode Exit fullscreen mode

setAttribute()

Sets or updates an attribute.

let link = document.querySelector("a");
link.setAttribute("href", "https://example.com");
console.log(link.getAttribute("href"));  
// Output: "https://example.com"
Enter fullscreen mode Exit fullscreen mode

hasAttribute()

Checks if an element has a specific attribute.

let button = document.querySelector("button");

if (button.hasAttribute("disabled")) {
    console.log("Button is disabled");
} else {
    console.log("Button is enabled");
}
Enter fullscreen mode Exit fullscreen mode

removeAttribute()

Removes an attribute from an element.

let input = document.querySelector("input");
input.removeAttribute("disabled");
Enter fullscreen mode Exit fullscreen mode

2. Working with class Attributes

classList.add()

Adds a class to an element.

let box = document.querySelector(".box");
box.classList.add("active");
Enter fullscreen mode Exit fullscreen mode

classList.remove()

Removes a class.

box.classList.remove("active");
Enter fullscreen mode Exit fullscreen mode

classList.toggle()

Toggles a class on/off.

box.classList.toggle("hidden");

Enter fullscreen mode Exit fullscreen mode

classList.contains()

Checks if an element has a class.

console.log(box.classList.contains("hidden"));  
// Output: true or false
Enter fullscreen mode Exit fullscreen mode

3. Working with data-* Attributes

Custom attributes (data-*) store additional data in elements.

Getting data-* Attributes

let button = document.querySelector("button");
console.log(button.getAttribute("data-user-id"));  
// Output: User ID stored in `data-user-id`
Enter fullscreen mode Exit fullscreen mode

Using dataset for Easier Access

console.log(button.dataset.userId);  
// Output: User ID stored in `data-user-id`
Enter fullscreen mode Exit fullscreen mode

Setting data-* Attributes

button.dataset.status = "active";
console.log(button.dataset.status);  
// Output: "active"
Enter fullscreen mode Exit fullscreen mode

4. Enabling/Disabling Elements (disabled Attribute)

let button = document.querySelector("button");

// Disable the button
button.setAttribute("disabled", true);

// Enable the button
button.removeAttribute("disabled");
Enter fullscreen mode Exit fullscreen mode

Manipulating Styles in JavaScript (DOM)

JavaScript allows you to dynamically change CSS styles on HTML elements using the style property or CSS classes.

1. Changing Inline Styles

You can modify CSS properties using the .style property.

let box = document.querySelector(".box");
box.style.backgroundColor = "blue";
box.style.color = "white";
box.style.padding = "20px";
Enter fullscreen mode Exit fullscreen mode

2. Modifying Multiple Styles Using cssText

box.style.cssText = "background: red; color: white; padding: 15px;";

Enter fullscreen mode Exit fullscreen mode

3. Using classList for CSS Manipulation

Instead of modifying styles directly, use CSS classes for better control.

Adding a Class

box.classList.add("highlight");
Enter fullscreen mode Exit fullscreen mode

Removing a Class

box.classList.remove("highlight");

Enter fullscreen mode Exit fullscreen mode

Toggling a Class (On/Off)

box.classList.toggle("hidden");

Enter fullscreen mode Exit fullscreen mode

Checking if an Element Has a Class

console.log(box.classList.contains("hidden"));  
// Output: true or false
Enter fullscreen mode Exit fullscreen mode

Navigating the Page Using JavaScript (DOM Navigation)

JavaScript provides various DOM navigation methods to move between elements on a web page.

Accessing Parent, Child, and Sibling Elements

Getting the Parent Element (parentNode & parentElement)

let child = document.querySelector(".child");
console.log(child.parentNode);   
console.log(child.parentElement);
Enter fullscreen mode Exit fullscreen mode
Feature                 Method
Get Parent Element  parentNode, parentElement
Get Child Elements  firstElementChild, lastElementChild
Get Sibling Elements    nextElementSibling, previousElementSibling
Scroll to Section   scrollIntoView()
Redirect to URL         window.location.href
Reload Page         window.location.reload()
Navigate History    window.history.back() / forward()
Enter fullscreen mode Exit fullscreen mode

Adding Elements to a Page Using JavaScript (DOM Manipulation)

JavaScript allows you to dynamically create and add elements to the webpage using the DOM API.

1. Creating and Appending an Element

createElement() + appendChild()

let newPara = document.createElement("p"); // Create <p> element
newPara.textContent = "This is a new paragraph!"; // Add text

document.body.appendChild(newPara); // Append to body
Enter fullscreen mode Exit fullscreen mode

2. Adding an Element Inside a Specific Parent

let parentDiv = document.getElementById("container");

let newDiv = document.createElement("div");
newDiv.textContent = "Hello, this is a new div!";
newDiv.classList.add("new-box");

parentDiv.appendChild(newDiv);
Enter fullscreen mode Exit fullscreen mode

3. Using insertBefore() (Insert at a Specific Position)

let list = document.getElementById("list");
let newItem = document.createElement("li");
newItem.textContent = "New Item";

let firstItem = list.firstElementChild; // Get first item
list.insertBefore(newItem, firstItem);  // Insert before it
Enter fullscreen mode Exit fullscreen mode
Feature                        Method
Create an Element          createElement("tag")
Add Text                   element.textContent = "Text"
Append to End                  appendChild(element)
Insert Before                  insertBefore(newElement, referenceElement)
Insert at Specific Position    insertAdjacentHTML(position, html)
Prepend Element                prepend(element)
Clone Element                  cloneNode(true)
Enter fullscreen mode Exit fullscreen mode

Removing Elements from a Page Using JavaScript (DOM Manipulation)

JavaScript allows you to remove elements dynamically from the DOM using various methods.

Removing an Element Using remove()

let element = document.getElementById("box");
element.remove();
Enter fullscreen mode Exit fullscreen mode

2. Removing a Child Element Using removeChild()

let parent = document.getElementById("container");
let child = document.getElementById("child");

parent.removeChild(child);
Enter fullscreen mode Exit fullscreen mode
Feature                       Method
Remove an element         element.remove()
Remove a child                parent.removeChild(child)
Remove first/last child       firstElementChild.remove() / lastElementChild.remove()
Remove all children       innerHTML = ""
Remove using parent       parentNode.removeChild(element)
Remove multiple elements      querySelectorAll().forEach(el => el.remove())
Enter fullscreen mode Exit fullscreen mode

DOM Events in JavaScript

DOM Events allow JavaScript to detect and respond to user interactions such as clicks, key presses, and mouse movements.

1. Adding an Event Listener (addEventListener)

let button = document.getElementById("myButton");

button.addEventListener("click", function() {
    console.log("Button clicked!");
});
Enter fullscreen mode Exit fullscreen mode

onclick and onmouseenter Events in JavaScript

JavaScript provides event handlers like onclick and onmouseenter to detect user interactions such as clicks and mouse movements.

1. onclick Event (Detects Clicks)

The onclick event fires when an element is clicked.

Using onclick with HTML (Inline)

<button onclick="alert('Button clicked!')">Click Me</button>
Enter fullscreen mode Exit fullscreen mode

Using onclick in JavaScript (Better Approach)

let button = document.getElementById("myButton");

button.onclick = function() {
    alert("Button clicked!");
};
Enter fullscreen mode Exit fullscreen mode

Using addEventListener("click") (Best Practice)

let btn = document.getElementById("myButton");

btn.addEventListener("click", () => {
    alert("Button clicked using addEventListener!");
});
Enter fullscreen mode Exit fullscreen mode

2. onmouseenter Event (Mouse Hover)

The onmouseenter event fires when the mouse enters an element.

Example: Changing Background Color on Hover

let box = document.getElementById("box");

box.onmouseenter = function() {
    box.style.backgroundColor = "yellow";
};

box.onmouseleave = function() {
    box.style.backgroundColor = "white";
};
Enter fullscreen mode Exit fullscreen mode

addEventListener() in JavaScript

The addEventListener() method allows JavaScript to attach event listeners to HTML elements dynamically.

It is the preferred method for handling events because it supports multiple handlers.

Basic Syntax

element.addEventListener("event", function);
Enter fullscreen mode Exit fullscreen mode

Event Listeners for Elements in JavaScript

JavaScript event listeners allow you to detect user interactions on elements like buttons, links, inputs, and forms.

1. Adding an Event Listener (addEventListener())

element.addEventListener("event", function);
Enter fullscreen mode Exit fullscreen mode

this in Event Listeners in JavaScript

The this keyword behaves differently in event listeners based on how the function is defined.

1. this in a Regular Function (Refers to the Element)

When using a regular function, this refers to the element that triggered the event.

let button = document.getElementById("myButton");

button.addEventListener("click", function() {
    console.log(this);  // Logs the button element
    this.style.backgroundColor = "blue"; // Changes button color
});
Enter fullscreen mode Exit fullscreen mode

Keyboard Events in JavaScript

JavaScript keyboard events allow you to detect when a user presses or releases a key.

1. Types of Keyboard Events

Event Description
keydown Fires when a key is pressed down
keyup Fires when a key is released
keypress (Deprecated) Similar to keydown, but does not detect Shift, Ctrl, Alt, etc.

Best Practice: Use keydown and keyup instead of keypress.

2. Detecting Key Press (keydown)

document.addEventListener("keydown", (event) => {
    console.log(`Key pressed: ${event.key}`);
});
Enter fullscreen mode Exit fullscreen mode

Form Events in JavaScript

JavaScript form events allow you to detect user interactions with form elements, such as input fields, checkboxes, and buttons.

1. Common Form Events

| Event | Description |
|-------|------------|
| `submit` | Fires when a form is submitted |
| `focus` | Fires when an input field gains focus |
| `blur` | Fires when an input field loses focus |
| `change` | Fires when an input value changes (for dropdowns, checkboxes, etc.) |
| `input` | Fires when the user types in an input field |
| `reset` | Fires when the form is reset |
Enter fullscreen mode Exit fullscreen mode

2. Prevent Default Form Submission (submit Event)

let form = document.getElementById("myForm");

form.addEventListener("submit", (event) => {
    event.preventDefault(); // Prevent page reload
    console.log("Form submitted!");
});
Enter fullscreen mode Exit fullscreen mode

Extracting Form Data in JavaScript

JavaScript allows you to retrieve form input values dynamically for validation, processing, or sending data to a server.

1. Extracting Data Using querySelector

document.getElementById("myForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent page reload

    let name = document.querySelector("#name").value;
    let email = document.querySelector("#email").value;
    let message = document.querySelector("#message").value;

    console.log(`Name: ${name}, Email: ${email}, Message: ${message}`);
});
Enter fullscreen mode Exit fullscreen mode

2. Extracting Data Using elements[]

document.getElementById("myForm").addEventListener("submit", function(event) {
    event.preventDefault();

    let form = event.target;
    let name = form.elements["name"].value;
    let email = form.elements["email"].value;

    console.log(`Name: ${name}, Email: ${email}`);
});
Enter fullscreen mode Exit fullscreen mode

3. Extracting Checkbox and Radio Button Values

document.getElementById("myForm").addEventListener("submit", function(event) {
    event.preventDefault();

    let agree = document.querySelector("#agree").checked;
    let gender = document.querySelector('input[name="gender"]:checked').value;

    console.log(`Agreement: ${agree}, Gender: ${gender}`);
});
Enter fullscreen mode Exit fullscreen mode
Feature                    Method
Get Input Value            document.querySelector("#id").value
Get Checkbox Value     document.querySelector("#id").checked
Get Selected Radio Value document.querySelector('input[name="name"]:checked').value
Get Dropdown Value     document.querySelector("#id").value
Extract All Form Data      new FormData(form).entries()
Send Data to Server    fetch("URL", { method: "POST", body: formData })
Enter fullscreen mode Exit fullscreen mode

change Event in JavaScript

The change event fires when a form input loses focus after a value change.

It is commonly used for dropdowns, checkboxes, radio buttons, and text inputs.

1. Basic Syntax

element.addEventListener("change", function(event) {
    console.log(event.target.value);
});
Enter fullscreen mode Exit fullscreen mode

input Event in JavaScript

The input event fires whenever the value of an input field changes, making it ideal for live updates.

1. Basic Syntax

element.addEventListener("input", function(event) {
    console.log(event.target.value);
});
Enter fullscreen mode Exit fullscreen mode

Event Bubbling in JavaScript

Event bubbling is a concept in the DOM where an event starts from the target element and propagates upwards to its ancestors.

1. How Event Bubbling Works

Consider the following HTML:

<div id="parent">
    <button id="child">Click Me</button>
</div>
Enter fullscreen mode Exit fullscreen mode

Now, let's add event listeners:

document.getElementById("child").addEventListener("click", () => {
    console.log("Child clicked!");
});

document.getElementById("parent").addEventListener("click", () => {
    console.log("Parent clicked!");
});
Enter fullscreen mode Exit fullscreen mode

Clicking the button logs:

Child clicked!
Parent clicked!

The event starts at the child (button) and bubbles up to the parent (div).

2. Stopping Event Bubbling (stopPropagation())

Use event.stopPropagation() to prevent bubbling:

document.getElementById("child").addEventListener("click", (event) => {
    event.stopPropagation();
    console.log("Child clicked!");
});

document.getElementById("parent").addEventListener("click", () => {
    console.log("Parent clicked!");
});
Enter fullscreen mode Exit fullscreen mode

Now, clicking the button only logs:

Child clicked!

The parent event is NOT triggered.

Event Delegation in JavaScript

Event Delegation is a technique in JavaScript where a single event listener is added to a parent element to handle events on multiple child elements, even if they are added dynamically.

1. Why Use Event Delegation?

🔹 Without Event Delegation (Adding Event Listeners to Each Button)

let buttons = document.querySelectorAll(".btn");

buttons.forEach(button => {
    button.addEventListener("click", () => {
        console.log("Button clicked!");
    });
});
Enter fullscreen mode Exit fullscreen mode

Does not work for dynamically added elements.

2. Using Event Delegation

document.getElementById("parent").addEventListener("click", (event) => {
    if (event.target.matches(".btn")) {
        console.log(`Button Clicked: ${event.target.textContent}`);
    }
});
Enter fullscreen mode Exit fullscreen mode

Why Use?

  • Only one event listener is needed.
  • Works for both existing and dynamically added elements.

Top comments (0)