Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12141

Add attribute & value to element using JavaScript

$
0
0

I'm creating a dark / light theme toggle for my website. I'm using a Bootstrap Nav bar on my site. I'm using a JavaScript event listener to change the theme. I need to change the Bootstrap Nav bar to be the dark theme version.

The problem I'm having is that when the 'dark theme' button is clicked, I want to be able to add data-bs-theme="dark" to my element. I tried using setAttribute (element.setAttribute("class", "democlass");) but this didn't work as it doesn't recognise 'data-bs-theme' as an attribute. Is there any other way I can do this?

I tried:function changeTheme() { let nav = document.querySelector("nav"); nav.setAttribute("data-bs-theme", "dark"); }but it didn't add data-bs-theme="dark" to the nav element.

Many thanks for your help!


Viewing all articles
Browse latest Browse all 12141

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>