Changing CSS styles with JavaScript - traditional vs modern approaches.
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>
</body>
</html>
JavaScript can change the style of an HTML element.
<!DOCTYPE html>
<html lang="en">
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" id="styleBtn">Apply Styles</button>
<button type="button" id="resetBtn">Reset Styles</button>
<script>
const demoText = document.getElementById('demo');
const styleButton = document.getElementById('styleBtn');
const resetButton = document.getElementById('resetBtn');
styleButton.addEventListener('click', () => {
demoText.style.fontSize = '35px';
demoText.style.color = '#0d6efd';
demoText.style.fontWeight = 'bold';
demoText.style.transition = 'all 0.3s ease';
});
resetButton.addEventListener('click', () => {
demoText.style.fontSize = '';
demoText.style.color = '';
demoText.style.fontWeight = '';
});
</script>
</body>
</html>
JavaScript can change the style of an HTML element.
const for variables (modern ES6+ syntax)element.style.propertyNamefont-size becomes fontSize)const, addEventListener, and arrow functions follows current best practices💡 Pro Tip:
For managing multiple style changes, consider using CSS classes instead of inline styles. Toggle classes with element.classList.add(), element.classList.remove(), or element.classList.toggle() for cleaner, more maintainable code!
Want to see how to use CSS classes for even cleaner style management?