JavaScript — Part 3
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()
Output:
Example: prepend()
Output:
Example: before()
Output:
Example: after()
Output:
Example: replaceWith()
Output:
Example: insertAdjacentHTML()
Output:
insertAdjacentHTML, insertAdjacentElement and insertAdjacentText:
1. insertAdjacentHTML()
Adds HTML code at a specific position relative to an element.
Positions
Example:
Output:
2. insertAdjacentElement()
Adds an actual DOM element (not HTML string) at a specific position.
Example:
Output:
3. insertAdjacentText()
Adds plain text at a specific position (no HTML parsing).
Example:
Output:
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
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:
Now, to get the timer id, we will store the setTimeout in the variable and then print it, as shown below:
Output: after 2 seconds
Can we also stop this from happening? Yes, we can do so by using the clearTimeout, as shown below:
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:
Output:
Example: setInterval()
Output: same output after every 2 seconds.
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
Output:
Example: mouse event
Output: when mouse came over the box
Example: keyboard events
Output:
When something was types in the input field:
Example: page load event
Output: console
Example: form submit event
Output:
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.
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
Example:
Example: The function inside setTimeout is a callback.
Example: callback with a message
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.
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.
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
After 5 seconds:
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)
After 5 seconds: error occurred as we wrote in the reject().
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:
Now, introducing the .then() and .catch():
Similarly, we are introducing .catch():
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()”
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
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.
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
Can we write p1.then() and define a new work? Yes, we can do so, as shown below:
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









