Using JavaScript, you may need to highlight some data or an element in your web page. Also, it enhances the element’s visibility using different colors and makes the overall web page more attractive. In such cases, adding and changing the background color of an element is very effective in catching the reader’s attention and improving the website design.
This write-up will guide you to change the element’s background in JavaScript.
How to Change an Element Background Color in JavaScript?
To change the background color of an element in JavaScript, apply the following techniques:
- backgroundColor property with color
- backgroundColor property with color code
The mentioned approaches will be demonstrated one by one!
Method 1: Change an Element Background Color in JavaScript Using backgroundColor Property With Color
The “backgroundColor” property sets the background color of the specified element. This property can be implemented on any of the added HTM elements by accessing its id and assigning it a background color.
Syntax
Here, the “object” refers to the element upon which the background color will be applied.
The following example explains the stated concept.
Example
In the example below, the heading tag <h> will be assigned an id named “id” and the “Background Color!” value:
Next, in the JavaScript file, the “document.getElementById()” method will access the “id” of the heading element. After that, the backgroundColor property will assign the color value “Lightgreen” against the id, which refers to the specified heading value in the previous step:
The output of the above implementation will result as follows:
In the output, it is observed that the background color is only applied to the selected heading element.
Method 2: Change an Element Background Color in JavaScript Using backgroundColor Property With Color Code
As discussed earlier, the “backgroundColor” property sets the background color of the specified element. This property can also be implemented upon the specified element using the RGB color code.
Look at the following example for demonstration:
Example
Firstly, we will add a paragraph using the <p> tag and assign it an id named “id” and a value as shown below:
Next, the “getElementById()” method will similarly access the paragraph element with the specified id and assign the background color using the backgroundColor property. Here, “#090” indicates the “RGB” code of medium dark shade of green color:
Output
In the above implementation, the green color is a result of “RGB->090”, in which 9 refers to the intensity of the green color.
Conclusion
To change the background color of an element in JavaScript, the “backgroundColor” property with the color method can be utilized to access the specific id and assign a particular background color. It is used with the “RGB” code to apply a specific shade of color to the selected HTML element. This article guided related to the method of changing the element’s background color in JavaScript.