Contenido del Curso
Advanced JavaScript Mastery
Advanced JavaScript Mastery
Modifying Element Styles
In web development, we often need to modify the element styles dynamically. JavaScript provides two primary ways to change the appearance of elements: updating inline styles using the style
property and managing classes with classList
.
Changing Inline Styles Using the style Property
The style
property in JavaScript allows you to directly modify the inline CSS of an HTML element. This method gives you full control over individual CSS properties but is limited to inline styles and only affects the specific element.
We can modify individual CSS properties using dot notation on the style object of an element. The property names are written in camelCase (e.g., backgroundColor
instead of background-color
).
index
index
index
The style
property is used to modify the inline styles of the #box
element. Each CSS property is accessed as an individual JavaScript property (e.g., box.style.backgroundColor
), allowing you to change specific aspects of the element's style dynamically.
Adding and Removing CSS Classes with classList
The classList
property provides a more flexible and powerful way to manage the styles of an element by adding, removing, or toggling CSS classes. This method is more maintainable than directly modifying inline styles, as it allows you to take advantage of external CSS files and keep your styling separate from your JavaScript logic.
index
index
index
classList.toggle()
is used to add or remove the highlight
class when the button is clicked. This method avoids cluttering the inline style
attribute and relies on pre-defined CSS rules for maintainability.
Practical Example: Switching Themes
Let's take a practical example where the user can switch between a light and dark theme using classList
.
index
index
index
classList.replace()
is used to swap the light-theme and dark-theme classes based on the current state.
¡Gracias por tus comentarios!