How to Change Button Color in JavaScript

Shraddha Paghdar Feb 02, 2024
  1. Buttons in HTML
  2. Use style.background to Change Button Color in JavaScript
How to Change Button Color in JavaScript

This article guides you on updating the button color through various methods so that you can easily start updating buttons on your websites.

Buttons in HTML

Buttons are an important part of any website. You need them for various functions, from sending information and accessing more content to linking to different parts of the website.

HTML offers you several ways to add buttons to your website: the button tag, the anchor link, and the button and submission input types.

The <button> tag in HTML defines the button that can be clicked. The <button> tag is used to send the content.

Images and text content can be placed within the <button> tag. Buttons can be styled with CSS.

Use style.background to Change Button Color in JavaScript

The getElementById() is an integrated document method provided by JavaScript that returns the element object whose id matches the specified id.

Syntax:

getElementById($id)

The $id is a mandatory parameter that specifies the id of an HTML attribute that must match. It returns the corresponding DOM element object if the corresponding element is found; otherwise, it returns null.

Now, let’s extract the button node element using getElementById().

<button onclick="changeColor()" id="btn">Change color</button>
function changeColor() {
  document.getElementById('btn').style.background = '#5e2e2e';
}

In the changeColor function, we use getElementById to find out the button element present in the DOM. Once the button node is found, extract the style object and update the background property with the desired color.

The ReadOnly style property returns the online style of an element in the form of a CSSstyledClaration object that contains a list of all the characteristics of the styles for the attributes defined in the attribute of the online style attribute.

Now let’s run the above code and click on the Change color button. It will change the button’s color and looks something like this.

Output:

change color in javascript

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

Related Article - JavaScript Button