Skip to main content

JavaScript HTML DOM Changing CSS

DOM allows JavaScript to change the style of HTML elements using style property.

Changing HTML Style

To change the style of an HTML element using JavaScript, you can use the style property.

As an example:

Editor

Loading...

In this example:

  • The getElementById() method is used to get the <p> element with the ID "myParagraph".
  • The style property is then used to change the color of the text to "red", the background color to "yellow", and the font size to "24px".
tip

The property names in JavaScript are in camelCase, whereas the CSS property names are in kebab-case. For example, the JavaScript property for background-color is backgroundColor.

Changin HTML style Using Events

You can change the style of an HTML element using events such as onmouseover , onmouseout and click.

As an example:

Editor

Loading...

In this example:

  • We have an HTML paragraph element with the ID "myParagraph" and a button element with the ID "myButton".
  • We use the getElementById() method to get references to these elements in JavaScript.
  • We use the addEventListener() method to attach a click event listener to the button.
  • When the button is clicked, the event listener function is executed, which changes the style of the paragraph element using the style property.

You can use any event, such as mouseover, mouseout, keydown, keyup, etc., to trigger the style change based on your specific use case.

Additionally, you can use CSS classes and toggle them using JavaScript to apply predefined styles, making your code more modular and maintainable.