Is there a way to toggle dark mode dynamically using Bootstrap's theme utilities?
Asked on Nov 03, 2025
Answer
Yes, you can dynamically toggle dark mode using Bootstrap's theme utilities by switching classes on a parent element. Here's a simple example using JavaScript to toggle between light and dark modes.
<!-- BEGIN COPY / PASTE -->
<div id="themeContainer" class="bg-light text-dark p-5">
<h1>Hello, World!</h1>
<button id="toggleTheme" class="btn btn-primary">Toggle Dark Mode</button>
</div>
<script>
document.getElementById('toggleTheme').addEventListener('click', function() {
const container = document.getElementById('themeContainer');
container.classList.toggle('bg-light');
container.classList.toggle('text-dark');
container.classList.toggle('bg-dark');
container.classList.toggle('text-light');
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with Bootstrap 5 best practices.- This example uses a button to toggle classes on a `div` with the id `themeContainer`.
- The `bg-light` and `text-dark` classes are used for light mode, while `bg-dark` and `text-light` are used for dark mode.
- The JavaScript `toggle` method is used to add or remove classes dynamically.
- Ensure that your HTML includes Bootstrap's CSS for the classes to work correctly.
Recommended Links: