-1

I have a div where is an HTML Attribute called data-theme inside. I want to ask how do I change the value of the Attribute called data-theme. For example: From: data-theme="dark" to data-theme="light". The value is stored in a variable as a string.

My div:

<div id="myId" data-theme="dark"></div>

I want to use normal JavaScript.

4
  • @MichaelHirschler that's explicitly about the <object>element Commented Feb 8, 2022 at 18:26
  • Does this answer your question? stackoverflow.com/questions/13524107/… Please see second answer for native JS. Commented Feb 8, 2022 at 18:30
  • document.getElementById("myId").dataset.theme="light"; Commented Feb 8, 2022 at 18:34
  • @LucaKiebel you're right. Second question is a better match for this :-) Commented Feb 9, 2022 at 9:25

1 Answer 1

0

document.getElementById("myId").setAttribute("data-theme", "newValue")

Sign up to request clarification or add additional context in comments.

1 Comment

Elements have a specialized dataset object which syncs with the corresponding data-attributes. document.getElementById("myId").dataset.theme="light";.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.