0

Here is the line i am trying to change.

<a class="weatherwidget-io" href="https://forecast7.com/en/n45d88170d50/dunedin/" data-label_1="DUNEDIN" data-label_2="WEATHER" data-theme="original" >DUNEDIN WEATHER</a>

I am trying to change the "original" data-theme="original" with "dark" when a function is triggered.

Here is my function

function darkmode() {
   
    document.body.classList.toggle("dark-theme")
    document.body.classList.toggle("logo_paw_dark")
    document.getElementsByName("data-theme").innerHTML = "dark";
    
}

I tried getting the element by the name but did not work and neither did with using id

  • 2
    Assuming you'd target the element by something like `document.querySelector('a.weatherwidget-io')`, you can access and modify its `data-theme` attributes by `.dataset.theme`. See this [MDN page](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes) for more details. – Bumhan Yu Apr 04 '22 at 00:57
  • 1
    Try `document.querySelector('[data-theme="original"]').setAttribute("data-theme", "dark")` – Louys Patrice Bessette Apr 04 '22 at 00:59
  • `document.getElementsByName("data-theme").innerHTML` doesn’t exist. See [What do querySelectorAll and getElementsBy\* methods return?](/q/10693845/4642212) and the [documentation](//developer.mozilla.org/en/docs/Web/API/Document/getElementsByName). – Sebastian Simon Apr 04 '22 at 01:38

1 Answers1

2

To change the actual attribute of data-theme, use:

document.documentElement.setAttribute('data-theme', 'dark');

But of course you need to define what element you're going to change. Here, I cannot recommend what you should do as it all depends on what you're trying to do. You can use id, class or queryselectors. Even use triggers such as onclick() etc. But.. But an id example here: First add an id to your , in this case let's call it "change-me".

Then:

document.getElementById("change-me").setAttribute('data-theme', 'dark');

To use queryselector, do this:

document.querySelector('[data-theme="original"]').setAttribute("data-theme", "dark")
Stoff
  • 517
  • 6
  • 22
  • still did not work here is what i have. `function darkmode() { document.body.classList.toggle("dark-theme") document.body.classList.toggle("logo_paw_dark") document.documentElement.setAttribute('data-theme', 'dark'); document.querySelector('[data-theme="original"]').setAttribute("data-theme", "dark") } ` –  Apr 04 '22 at 02:19
  • it does not like the .setAttribute bit at the end. –  Apr 04 '22 at 02:28
  • What happens for you? – Stoff Apr 04 '22 at 08:19