Sitemap
Aditya Kumar

Aditya Kumar

BTech | Security Software Engineer & Researcher | Cloud Security | Python, AWS, MERN, ReactJS | Mail: adii.utsav@gmail.com

JavaScript — Part 3

12 min readFeb 17, 2026
Press enter or click to view image in full size

HTML Insertion Methods:

HTML Insertion Methods — From Basics

HTML insertion methods are used to add new HTML elements to the page using JavaScript.

Example: append()

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size

Example: prepend()

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size

Example: before()

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size

Example: after()

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size

Example: replaceWith()

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size

Example: insertAdjacentHTML()

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size

insertAdjacentHTML, insertAdjacentElement and insertAdjacentText:

1. insertAdjacentHTML()

Adds HTML code at a specific position relative to an element.

Positions

Example:

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size

2. insertAdjacentElement()

Adds an actual DOM element (not HTML string) at a specific position.

Example:

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size

3. insertAdjacentText()

Adds plain text at a specific position (no HTML parsing).

Example:

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size

Changing HTML Classes using JavaScript: className and classList

What is a Class in HTML?

A class is used to style or identify an element.

Example:

<p class=”red”>Hello</p>

1. className (Basic Method)

Definition

className gets or sets the entire class attribute as a plain string.

Meaning

Setting className replaces all existing classes.

Example

element.className = “highlight”;

2. classList (Modern and Better Method)

Definition

classList provides a list of all classes on the element and allows you to add, remove, toggle, or check classes.

classList Methods

Simple Examples

Using className

<div id=”box”>Hello</div>

<script>

document.getElementById(“box”).className = “blue”;

</script>

This sets the class to exactly “blue”.

Using classList.add()

element.classList.add(“active”);

Using classList.remove()

element.classList.remove(“active”);

Using classList.toggle()

element.classList.toggle(“dark”);

Using classList.contains()

element.classList.contains(“active”); // true or false

Using classList.replace()

element.classList.replace(“old”, “new”);

setInterval and setTimeout in JavaScript:

setTimeout: Runs a function once after a given time (delay in milliseconds).

Syntax:

setTimeout(function, delay);

setInterval: Runs a function again and again after a fixed time interval.

Syntax:

setInterval(function, interval);

To understand this, let’s take a basic example:

Example: a basic example of creating a alert box

Press enter or click to view image in full size

What if we want that this should come 2 seconds later the page loaded, for this we will use setTimeout, as shown below:

Just after 2 seconds:

Press enter or click to view image in full size

Now, to get the timer id, we will store the setTimeout in the variable and then print it, as shown below:

Press enter or click to view image in full size

Output: after 2 seconds

Press enter or click to view image in full size

Can we also stop this from happening? Yes, we can do so by using the clearTimeout, as shown below:

Press enter or click to view image in full size

Output: no alert box will come this time.

Now, program to take user entry, where user will say yes or no, in order to use the clearTimeout, as shown below:

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size
Press enter or click to view image in full size

Example: setInterval()

Output: same output after every 2 seconds.

Press enter or click to view image in full size

setInterval and setTimeout in JavaScript:

What is an event?

An event is something that happens in the browser.
Example events:

· A button is clicked

· A key is pressed

· A page finishes loading

· Mouse moves

· A form is submitted

Your JavaScript code can listen to these events and react to them.

What is an Event Listener?

An event listener is a function that waits for an event to happen and runs when the event occurs.

Syntax:

element.addEventListener(“eventName”, function);

Common Browser Events

Example: click event

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size
Press enter or click to view image in full size

Example: mouse event

Press enter or click to view image in full size

Output: when mouse came over the box

Press enter or click to view image in full size

Example: keyboard events

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size

When something was types in the input field:

Example: page load event

Press enter or click to view image in full size

Output: console

Press enter or click to view image in full size

Example: form submit event

Press enter or click to view image in full size

Output:

Press enter or click to view image in full size

Handling Browser Events:

Get Aditya Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

What does “handling an event” mean?

Handling an event means:

1. Detecting when something happens (click, key press, mouse move, etc.)

2. Running code in response.

Example:
“User clicks a button → show a message”

Three Ways to Handle Events

In JavaScript, events can be handled in 3 ways:

Method 1 → HTML Event Attribute (old method)

You put the event directly in HTML.

Example:

<button onclick=”alert(‘Button clicked!’)”>Click</button>

Cons: Not recommended now. Mixes HTML & JS.

Method 2 → Assign event to element property

Simple and clean.

Example:

<button id=”btn”>Click</button>

<script>

document.getElementById(“btn”).onclick = function () {

alert(“Clicked!”);

};

</script>

Limitation:
You can assign only ONE function to .onclick.

Method 3 → addEventListener (best method)

Most modern and flexible method.

Example:

<button id=”btn”>Click</button>

<script>

document.getElementById(“btn”).addEventListener(“click”, () => {

alert(“Button clicked using addEventListener!”);

});

</script>

Advantages:

· You can attach multiple event handlers

· Works with all event types

· Better for real projects

Also,

Removing Event Listeners

You can remove an event only if it is stored in a function.

Press enter or click to view image in full size

Introduction to Callbacks:

What is a Callback?

A callback is a function that you pass as an argument to another function so that it can run later.

In simple words:

A callback = a function you give to another function to call when it is needed.

Why do we use Callbacks?

Because JavaScript does not wait for things like:

· setTimeout

· file loading

· API requests

· animations

· user actions

So, we use callbacks to run code after something finishes.

Example: a basic example of callback

Press enter or click to view image in full size

Example:

Press enter or click to view image in full size

Example: The function inside setTimeout is a callback.

Press enter or click to view image in full size

Example: callback with a message

Press enter or click to view image in full size

Callback Hell & Pyramid of Doom:

What is Callback Hell?

Callback Hell happens when you have too many callbacks inside each other, making the code look messy, confusing, and hard to read.

Simply:

Callback Hell = too many nested functions.

What Causes Callback Hell?

Callback hell happens when:

· Each task depends on the previous one

· And each task uses a callback

· So you keep nesting functions inside functions

Example:
Task 1 → inside it Task 2 → inside it Task 3 → inside it Task 4

This creates deep nesting.

What is the Pyramid of Doom?

When callbacks keep going inward (right side more and more), the code shape looks like a pyramid or stairs.

Example: callback hell

Why is Callback Hell Bad?

· Hard to read

· Hard to understand

· Hard to debug

· Hard to maintain

· Hard to add new code

· Errors become difficult to handle

Solution: Use Promises or async/await.

Introduction to Promises:

What is a Promise?

A Promise in JavaScript is an object that represents a value that will be available now, later, or never.
It’s used to handle asynchronous operations (things that take time).

A Promise can be in 3 states:

· pending → still running

· fulfilled → completed successfully

· rejected → failed

Other Important Details About Promises

· A Promise represents something that takes time, like fetching data from a server.

· .then() handles successful results.

· .catch() handles errors.

· .finally() runs no matter what (optional).

· Promises help avoid callback hell.

· Very commonly used with fetch() and async/await.

Syntax of promise:

let promise = new Promise(function(resolve, reject) {

// Do some work…

// If successful:

resolve(value);

// If an error happens:

reject(error);

});

Example: a basic example where the “World” will be printed 2 seconds after everything else is printed.

Press enter or click to view image in full size

Example: introducing promise in the code, basically we are saying that if the promise is fulfilled then resolve it as 59, later we printed it as well.

Press enter or click to view image in full size

When the code runs, the Promise is created and the function inside it runs immediately, so the first thing printed is “Hello.” The Promise is then resolved with the value 59. After that, the next line prints “Hello2.” The setTimeout schedules the message “World” to be printed after 2 seconds, but it does not run immediately. The script continues, printing “Hey Aditya,” and then it prints the Promise object itself, which shows Promise { 59 } because it was already resolved. Finally, after a 2-second delay, the scheduled message “World” is printed.

Promise .then() and .catch():

What is .then()?

.then() is used to run some code when a Promise is successfully resolved.The value passed to resolve() becomes the value received by .then().

What is .catch()?

.catch() is used to run some code when a Promise is rejected (when something goes wrong). The value passed to reject() becomes the error received by .catch().

Example: a basic code to understand the promise use case

Press enter or click to view image in full size

After 5 seconds:

Press enter or click to view image in full size

When the code starts running, a new Promise is created, and the message “Promise is pending …” is printed immediately because the code inside a Promise runs right away. The setTimeout schedules the promise to resolve after 5 seconds, but it does not run yet. Then the line console.log(promise) is executed, and since the 5 seconds have not passed, it prints the Promise in its pending state: Promise { <pending> }. After 5 seconds, the function inside setTimeout runs, printing “I am a promise and I am resolved”, and the Promise finally becomes resolved with the value true.

Example: a promise which has been fulfilled and rejected. (Note: Fulfilled then it can either be resolved or rejected)

Press enter or click to view image in full size

After 5 seconds: error occurred as we wrote in the reject().

Press enter or click to view image in full size

Also, promises executes parallelly. It means if we have multiple promises, either getting resolved or rejected, they all can work in parallel. As shown below:

Press enter or click to view image in full size

Now, introducing the .then() and .catch():

Press enter or click to view image in full size

Similarly, we are introducing .catch():

Press enter or click to view image in full size

Promise Chaining .then() calls:

What is Promise Chaining?

Promise chaining means using multiple .then() one after another, where the output of one .then() becomes the input of the next.

Each .then() returns a new Promise, allowing you to run steps in order.

Why use Promise chaining?

· To perform tasks step-by-step

· To avoid callback hell

· To make async code readable and organised

Example: a very basic example of promise with “.then()”

Press enter or click to view image in full size

Above code creates a Promise (p1) that waits 2 seconds and then prints “Resolved after 2 seconds” before successfully completing with the value 59. When the promise finishes, the .then() function runs and prints that resolved value (59). In simple terms: “Wait 2 seconds, show a message, return 59, then print 59.”

Example: promise chaining basics

Press enter or click to view image in full size

This code shows promise chaining. The first promise (p1) waits 2 seconds, prints “Resolved after 2 seconds”, and resolves with 59. The first .then() receives that value, prints 59, and then creates and returns another promise (p2), which immediately resolves with “Promise p2 resolved”. Because it returns a promise, the next .then() waits for p2 to finish, then prints “We are done” followed by the message from p2. In short: wait 2 seconds → print 59 → run another promise → print final messages.

Example: another example of promise chaining.

Press enter or click to view image in full size

This code shows two promises running one after another. First, p1 waits 2 seconds, prints “Resolved after 2 seconds”, and resolves with 59. Inside the first .then(), that value (59) is printed, and a second promise p2 is created. p2 also waits 2 seconds before resolving with “Promise 2 resolved”. Because the .then()returnsp2, the next .then()` waits for it to finish, then prints “We are done” and the final message.

Attaching Multiple Handlers to a Promise:

You can attach more than one .then() or .catch() to the same Promise. Each handler will run independently when the Promise is resolved or rejected.

The key point: Every .then() attached to the same Promise runs separately. They do NOT depend on each other.

Example: a very basic promise created in JS

Press enter or click to view image in full size

Can we write p1.then() and define a new work? Yes, we can do so, as shown below:

Press enter or click to view image in full size

Each p.then() works independently.

Contact Me:
📧 Email: adii.utsav@gmail.com
🔗 LinkedIn: https://www.linkedin.com/in/aditya-kumar-3241b6286/
💻 GitHub: https://github.com/Rememberful

--

--

Aditya Kumar
Aditya Kumar

Written by Aditya Kumar

BTech | Security Software Engineer & Researcher | Cloud Security | Python, AWS, MERN, ReactJS | Mail: adii.utsav@gmail.com