How to make button on JavaScript

Learn how to create a button with JavaScript! Step-by-step guide with example code to help you get started.

Creating a Button Using JavaScript

JavaScript is a great language for creating interactive user interfaces. It can be used to create buttons, submit forms, and perform other tasks. In this tutorial, we will learn how to create a button using JavaScript.

The first step is to create a <button> element. This can be done with the following code:

let myButton = document.createElement("button");

The document.createElement() method creates a new HTML element and returns a reference to it. In this case, we are creating a <button> element.

Next, we need to set the text that will appear on the button. This is done using the innerHTML property:

myButton.innerHTML = "Click Me!";

Now that we have created the button, we need to add it to the page. We can do this using the appendChild() method:

document.body.appendChild(myButton);

Finally, we need to add an event listener to the button. This will allow us to execute a function when the button is clicked. We can do this using the addEventListener() method:

myButton.addEventListener("click", function(){
    alert("Button was clicked!");
});

Now that we have created the button, it is ready to be used!

Answers (0)