DEV Community

Sathish 226
Sathish 226

Posted on

Day 2 - Session 2: JavaScript — DOM, Variables, and Interactivity

Another day, another JavaScript adventure!

Welcome back to Day 2, Session 2 of our JavaScript series. Today we’ll connect our HTML page with JavaScript to make it interactive. We’ll cover:

➤ The DOM (Document Object Model)
➤ Global vs Local Variables
alert() popups
➤ Button onclick events
➤ Logging from HTML to the console

1.What is the DOM?

The DOM is how JavaScript sees and interacts with your HTML page.
It lets you select, change, and control elements on the page.

Example: Select an element by ID

let title = document.getElementById("main-title");
console.log(title);
Enter fullscreen mode Exit fullscreen mode

This grabs:

<h1 id="main-title">Welcome!</h1>
Enter fullscreen mode Exit fullscreen mode

2.Global vs Local Variables:

Global → accessible anywhere

Local → accessible only inside a function

Example:

let globalVar = "I'm global";

function testScope() {
    let localVar = "I'm local";
    console.log(globalVar); //  Works
    console.log(localVar);  //  Works
}

console.log(globalVar); //  Works
console.log(localVar);  //  Error: localVar is not defined
Enter fullscreen mode Exit fullscreen mode

||Tip||: Avoid too many global variables to keep code clean.

3.Showing Alerts:

Want to pop up a message box?
Use:

alert("Hello, this is an alert!");
Enter fullscreen mode Exit fullscreen mode

This shows a simple browser popup.

4.Button OnClick Event:

We can make buttons interactive using onclick.

Example HTML:

<button onclick="showMessage()">Click Me!</button>
Enter fullscreen mode Exit fullscreen mode

Example js

function showMessage() {
    alert("Button was clicked!");
}
Enter fullscreen mode Exit fullscreen mode

||Tip||: You can also use addEventListener for more control.

5.From HTML to Console:

To send messages to the console(for debugging or tracking), use:

console.log("This message appears in the console.");
Enter fullscreen mode Exit fullscreen mode

Open the DevTools Console in your browser (usually right-click → Inspect → Console) to see it.

Quick Recap:

  • Learned how the DOM connects JS to HTML
  • Understood global vs local variables
  • Used alert() popups
  • Added onclick interactivity
  • Logged messages to the console

That wraps up Session 2!

Thanks for following along — keep coding, and see you next time!!

Top comments (0)