How to make a button on JavaScript

How to create a button on JavaScript: an example of using doocument.createlement () to create and configure the button.

Creating a Button with JavaScript

Creating a button with JavaScript is a simple process. We will use the document.createElement() method to create a button element. This method takes a single parameter which is the type of element that we want to create. In this case, we will use the value 'button'.

const button = document.createElement('button');

After creating the button element, we can add some properties to it. For example, we can set the text that appears on the button using the innerText property.

button.innerText = 'Click Me!';

We can also set the background color of the button using the style.backgroundColor property. Let's set it to a light blue color.

button.style.backgroundColor = '#add8e6';

After setting up the properties of the button, we can add it to the page. To do this, we can use the appendChild() method on the document.body element.

document.body.appendChild(button);

Now that the button is on the page, we can add an event listener to it that will be called when the button is clicked. We can use the addEventListener() method to do this. This method takes two parameters, the type of event that we want to listen for and a callback function to be called when the event fires.

button.addEventListener('click', () => {
  console.log('Button was clicked!');
});

And that's it! We've successfully created a button with JavaScript and added an event listener to it that will be called when the user clicks the button.

Answers (0)