"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

Events and DOM Manipulation

 

JavaScript allows you to interact with web pages by manipulating the DOM (Document Object Model) and responding to events like clicks, form submissions, or mouse movements.


What is the DOM?

The DOM is a programming interface for HTML and XML documents. It represents the page as a tree of nodes, where JavaScript can:

  • Read and change content
  • Modify styles and attributes
  • Add or remove elements

Selecting Elements

You can select HTML elements using various DOM methods:

// Select by ID

let heading = document.getElementById("myHeading");

 

// Select first matching element

let firstParagraph = document.querySelector(".paragraph");

 

// Select all matching elements

let allParagraphs = document.querySelectorAll("p");


Changing Content and Styles

let heading = document.getElementById("myHeading");

 

// Change text content

heading.textContent = "Hello, JavaScript!";

 

// Change HTML content

heading.innerHTML = "<span style='color: red;'>Red Text</span>";

 

// Change styles

heading.style.color = "blue";

heading.style.fontSize = "24px";


Adding Event Listeners

There are two main ways to handle events:

// Inline (Not recommended for large apps)

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

 

// Using addEventListener (Recommended)

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

btn.addEventListener("click", function() {

  alert("Button clicked!");

});


Handling Common Events

// Click Event

document.getElementById("myButton").addEventListener("click", () => {

  console.log("Button was clicked!");

});

 

// Submit Event

document.getElementById("myForm").addEventListener("submit", (event) => {

  event.preventDefault(); // Prevent form from refreshing page

  console.log("Form submitted!");

});

 

// Mouseover Event

document.getElementById("myBox").addEventListener("mouseover", () => {

  console.log("Mouse is over the box!");

});

 

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)