DOM Manipulation: Styles and classList
Controlling the visual presentation of HTML elements is a core part of dynamic web development. JavaScript allows you to change an element's inline styles directly or, more commonly and effectively, manage its CSS classes, which in turn apply predefined styles.
This lesson explores how to work with an element's style property and the powerful classList API.
1. Direct Inline Style Manipulation (element.style)
Every HTML element has a style property, which is an object representing the element's inline CSS styles. You can access and modify individual CSS properties directly through this object.
- Accessing:
element.style.propertyName - Setting:
element.style.propertyName = 'value';
Key Considerations:
- CSS Property Naming: CSS properties that contain hyphens (e.g.,
background-color,font-size) must be converted to camelCase when accessed via thestyleobject (e.g.,backgroundColor,fontSize). - Values as Strings: All values must be set as strings, including units (e.g.,
'10px','red','block'). - Inline Styles Only: This method only affects the inline
style=""attribute of the element. It does not modify styles defined in CSS stylesheets (external or internal<style>tags). Inline styles have high specificity and often override styles from stylesheets. - Specificity & Overrides: Be aware that inline styles generated this way will override styles from external stylesheets due to CSS specificity rules.
- Performance: Can be less performant for multiple style changes compared to toggling classes, as each change triggers a re-render.
2. Managing CSS Classes (element.classList)
Managing an element's CSS classes is generally the preferred method for changing styles, as it cleanly separates concerns: CSS defines the styles, and JavaScript controls which styles are applied by manipulating classes. The classList property provides a convenient way to add, remove, and toggle classes.
The classList property returns a DOMTokenList object, which has several useful methods:
add(className1, className2, ...): Adds one or more class names to the element.remove(className1, className2, ...): Removes one or more class names from the element.toggle(className, force): Toggles the presence of a class name. If the class exists, it's removed; if not, it's added. The optionalforceboolean argument (true/false) can be used to add/remove the class unconditionally.contains(className): Checks if the element has a specific class name. Returnstrueorfalse.replace(oldClassName, newClassName): Replaces an existing class name with a new one.
3. Best Practices: element.style vs. element.classList
-
Prefer
classListfor most styling changes.- Separation of Concerns: Keep presentation (CSS) in stylesheets and behavior (JavaScript) in JavaScript.
- Maintainability: Easier to manage complex styles and states. Instead of setting 10 inline styles, you just add one class.
- Readability: Code is cleaner when you toggle semantic classes like
active,hidden,errorinstead of manipulating many individual style properties. - Performance: Toggling classes can sometimes lead to better performance for large style changes, as the browser can apply optimized CSS rules.
-
Use
element.stylewhen:- You need to apply a truly dynamic, unique style value that cannot be predetermined in CSS (e.g., setting an element's
leftposition based on mouse coordinates, or dynamically calculatedwidth). - You are applying very few, simple, one-off inline styles.
- You need to quickly override an existing stylesheet rule and are aware of the specificity implications.
- You need to apply a truly dynamic, unique style value that cannot be predetermined in CSS (e.g., setting an element's
In summary: For state-driven visual changes, use classList. For dynamic, unique pixel/color values that aren't part of a predefined state, use element.style.
Exercise: Style and Class Manipulator
Instructions: Given the following (simulated) HTML structure and basic CSS, manipulate its styles and classes.
<style>
.box {
width: 120px;
height: 120px;
border: 2px solid grey;
margin: 10px;
display: inline-block;
vertical-align: top;
font-family: Arial, sans-serif;
text-align: center;
line-height: 120px;
}
.default-bg { background-color: #f0f0f0; }
.highlight-border { border-color: blue; border-width: 4px; }
.warning-bg { background-color: orange; color: white; }
.hide { display: none; }
.rounded-corners { border-radius: 15px; }
</style>
<div id="element1" class="box default-bg">Element 1</div>
<div id="element2" class="box default-bg">Element 2</div>
<button id="toggleHighlight">Toggle Highlight (E1)</button>
<button id="changeToWarning">Set Warning (E2)</button>
<button id="hideElement1">Hide Element 1</button>
<button id="makeElement1Round">Make Element 1 Round</button>
<button id="dynamicSize">Dynamic Size (E1)</button>
Your Task:
- Toggle Class:
- Select
element1. - When
toggleHighlightbutton is clicked, toggle thehighlight-borderclass onelement1. Logelement1.classNameafter each toggle.
- Select
- Add/Remove Class:
- Select
element2. - When
changeToWarningbutton is clicked, removedefault-bgand addwarning-bgtoelement2. Logelement2.className.
- Select
- Toggle Display:
- Select
element1. - When
hideElement1button is clicked, toggle thehideclass onelement1.
- Select
- Direct Style (Single Property):
- Select
element1. - When
makeElement1Roundbutton is clicked, setelement1.style.borderRadiusto'50%'. Log itsborderRadiusstyle.
- Select
- Direct Style (Dynamic):
- Select
element1. - When
dynamicSizebutton is clicked, change itswidthto a random size between 100px and 200px, and itsheightto a random size between 50px and 150px. UseMath.random()andMath.floor().
- Select

