Menu

Selecting Elements and Responding to Clicks

Selecting Elements and Responding to Clicks

To make JavaScript affect your HTML, you first need to grab the element you want to work with. document.querySelector is the most common way to do this, using the same selectors you use in CSS.

Once you have the element, you can listen for an event, like a click, and run a function when that event happens.

const button = document.querySelector("#contact button");

 

button.addEventListener("click", function (event) {

  event.preventDefault();

  alert("Thanks for reaching out! We will reply soon.");

});

Explanation:

  • querySelector finds the first button inside the element with id contact.
  • addEventListener attaches a click listener.
  • event.preventDefault stops the browser’s default form submission, preventing the page from reloading while JavaScript handles the form.
  • alert shows a simple popup message to the visitor.

HTML Tutorial (From Basics to Implementation)

AP

Abhishek Pati





Get in Touch For Details