How to Create a Button to Change the Size of a Heading in JavaScript?

Estimated read time 2 min read

You can create a button to change the size of a heading in JavaScript by using the following steps:

  1. Select the heading element you want to change the size of. You can use the document.querySelector method to select the heading element by its tag name, class name, or id. For example, to select a heading element with the id “myHeading”, you would use the following code:
const heading = document.querySelector("#myHeading");

Create a button element and add it to the HTML page. You can use the document.createElement method to create a button element, and the document.body.appendChild method to add it to the page. For example:

const button = document.createElement("button");
button.innerHTML = "Change Size";
document.body.appendChild(button);

Add an event listener to the button to change the size of the heading when the button is clicked. You can use the addEventListener method to attach a click event to the button, and then use JavaScript to change the size of the heading element. For example:

let size = 16;
button.addEventListener("click", function() {
  size += 2;
  heading.style.fontSize = size + "px";
});

Here’s the complete code:

const heading = document.querySelector("#myHeading");
const button = document.createElement("button");
button.innerHTML = "Change Size";
document.body.appendChild(button);

let size = 16;
button.addEventListener("click", function() {
  size += 2;
  heading.style.fontSize = size + "px";
});

With this code, each time the button is clicked, the size of the heading will be increased by 2 pixels.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply