How a Birthday Cake Accidentally Taught Me DOM πŸŽ‚



This content originally appeared on DEV Community and was authored by Lokesh Keswani

Yesterday, I went to buy a birthday cake for my friend.
Nothing special, just a chocolate truffle.

But somehow, it turned into a full-blown chaotic adventure.

The shopkeeper put the cake on the counter. I said:

β€œWait, can you write β€˜Happy Birthday’ on it?”

He nodded.

Then I saw the candles.

β€œPlace 10 candles evenly around the cake.”

He did.

Then my friend called:

β€œMake sure the sprinkles are on top, not falling on the plate!”

At this point, the shopkeeper looked like he was solving a multi-level puzzle.
He carefully moved the candles, repositioned the sprinkles, and even adjusted the chocolate curls.

Then someone sneezed. Sprinkles shifted.
The candle placement got slightly off.
I had to ask him again to β€œfix the font on the writing.”

By the time we were done, the cake looked perfectβ€”but it had taken 20 adjustments, 15 requests, and 3 mini heart attacks.

Right thereβ€”just like DOM.

No wonder the cake needed a DOM intervention.

DOM is nothing but changing parts of a webpage using JavaScript.
You can:

  • Select elements
  • Change content
  • Change style
  • Add or remove elements
  • Attach events

Let’s see how it works, step by step, with our cake example.

Step 1: Selecting Elements

First, you need to pick what you want to change:

let candles = document.querySelectorAll(".candle");
let sprinkles = document.querySelector("#sprinkles");
let writing = document.querySelector("#writing");

Candles, sprinkles, and writing on the cake = HTML elements.

Step 2: Changing Content

Updating text or numbers:

writing.innerText = "Happy Birthday!";

Just like asking the shopkeeper to write the correct name on the cake.

Step 3: Changing Style

Adjusting colors, positions, fonts:

candles.forEach(c => c.style.top = "10px");
sprinkles.style.color = "red";

Exactly like moving sprinkles and candles so they look perfect.

Step 4: Adding & Removing Elements

Adding extra decorations:

let chocolate = document.createElement("div");
chocolate.innerText = "Chocolate Curl 🍫";
document.body.appendChild(chocolate);

Removing a candle someone blew out accidentally:

candles[2].remove();

Step 5: Attaching Events

Making elements respond to actions:

candles.forEach(c => c.addEventListener("blow", () => {
  c.style.display = "none";
}));

Just like candles disappearing when someone blows them out.

By the end, our cake looked perfect…
but I was exhausted from micromanaging every tiny detail.

Moral? DOM is basically being the shopkeeper of your own chaotic webpage:

  • Pick elements
  • Change content
  • Adjust style
  • Add/remove stuff
  • Handle unpredictable events

And just like with the cake, if you don’t handle it properly…
your webpage can quickly turn into a mess!


This content originally appeared on DEV Community and was authored by Lokesh Keswani