In this blog post, we will explore different ways to apply styling to DOM elements dynamically using plain JavaScript. Whether you need to change the color, border, or any other CSS property of an element, we’ve got you covered.

Adding and Removing Classes

One of the cleanest approaches to styling elements is by using classes in your CSS. To apply or remove classes from an element, you can utilize the classList property along with its add() and remove() methods.

For instance, let’s say you have an element with the id my-element. You can select it using document.querySelector('#my-element'). Then, to add a class to the element, you would use classList.add('myclass'). To remove the class, simply call classList.remove('myclass').

Changing CSS Properties

Alternatively, you can directly modify specific CSS properties of an element by using the style property. This property references the element’s inline styles. With it, you have the flexibility to change various CSS properties programmatically.

For example, to change the color of an element, you can set the color property of the element’s style property:

element.style.color = '#fff';

Likewise, to modify the border, you can adjust the border property:

element.style.border = '1px solid black';

You can change any CSS property this way, simply by using camelCase instead of dashes when the CSS property name contains them. To discover a complete list of CSS properties and their respective translations, you can refer to the MDN page on CSS Properties Reference.

Now that you have learned different methods to style DOM elements using JavaScript, you can apply dynamic styles to enhance your web pages effortlessly.