See Also: Top 7 Hands-On HTML CSS Projects For Beginners To Practice
Table of Contents
Process of changing CSS using JS
1. Select the HTML element that you want to modify
- You can use techniques like ‘getElementById,’ ‘querySelector,’ or ‘getElementsByClassName’ to select the element based on its class, tag name, or ID.
2. Access the ‘style’ property of the selected element
- The ‘style’ property allows you to modify the CSS properties of the selected element.
- You can modify CSS properties by assigning new values to the corresponding properties of the ‘style‘ object. For example, to change the background color of an element, you can assign a new color value to the ‘backgroundColor’ property of the ‘style’ object.
4. Save the changes by applying the modified CSS to the element
- The changes will only work properly once the user applies them to the designated element. You can do this by assigning the modified element back to the original HTML element or by using the ‘setAttribute’ method to alter the element’s inline style.
In this example, we select the ‘div’ element with the ID ‘”myDiv,”‘ and then we modify its background color and text color and add a CSS class called ” highlight.”‘ When the ‘changeCSS‘ function is called by clicking the button, the changes take effect on the selected element.
Change CSS styles using JS
To change CSS styles using JS, you can use the style property of the HTML element you want to modify.
- For example, you can apply the following code if you wish to change the color of a ‘div’ element:
This code gets the ‘div’ element with the ‘id’ of ‘”myDiv”‘ using the ‘getElementById‘ method and assigns it to the ‘div’ variable. Then, it changes the ‘color’ property of the ‘style’ object of the ‘div’ element to ‘”red.”‘
- You can also change other CSS properties, such as ‘backgroundColor,’ ‘fontSize,’ and ‘fontWeight,’ etc., by modifying the corresponding properties of the ‘style’ object.
In this example, the add method adds a CSS class called ‘”highlight”‘ to the ‘div’ element, which can be defined in a stylesheet. The ‘remove’ method removes the ‘”highlight”‘ class from the ‘div’ element.
This code selects the ‘div’ element with the ‘id’ of ‘”myDiv”‘ using the ‘getElementById’ method and assigns it to the ‘div’ variable. Then, it changes the background color of the ‘div’ element to ‘”blue”‘ by modifying the ‘backgroundColor’ property of the ‘style’ object of the ‘div’ element. It also changes the font size to ‘”24px”‘ and font weight to ‘”bold”‘ by modifying the ‘fontSize’ and ‘fontWeight’ properties, respectively.
- You can also modify multiple styles at once by chaining the style properties together:
In this example, the ‘cssText’ property sets the CSS styles of the ‘div’ element all at once, using a CSS-like syntax. Semicolons separate the properties and their values; the entire string is enclosed in quotes.