-1

I want to change content by using a toggler.

This is the HTML structuring the content:

Snippet 1

<h3 id="pricing"><span id="status"></span></h3>

This is the JS for dynamically changing the content, when clicking toggler:

Snippet 2

var intervall = document.getElementById("status");

intervall.innerHTML = "month";

input.addEventListener("change", function () {
  if (this.checked) {
    intervall.innerHTML = "year";
  } else {
    intervall.innerHTML = "month";
  }
});

Console loggs that intervall is null.

I changed the HTML to this:

Snippet 3

<h3 id="pricing"></h3>
<p id="status"></p>

And code works. But I did not understand, why it is null in the first case. Once I had a similar problem. In this case a checkbox I wanted to target was hidden by another element. My guess was, that maybe the id="pricing" in the first HTML Codes "hides" the span element. So I tried this:

Snippet 4

var intervall = document.querySelector("#pricing span");

Resulting also in "intervall is null".

Could anyone explain why my solutions does not work but works in the case of snippet 3?

S.H
  • 365
  • 3
  • 13
  • 1
    What's `input`? Can you edit your question to include a [mcve]? I just threw an example together and [it works](https://jsfiddle.net/j08691/da3y7joq/1/), so you'll need to show us your non-functioning example – j08691 Apr 30 '21 at 18:16
  • Are you setting the innerHTML of "pricing" h3 tag anywhere? because in that case span would be overwritten and would give null – Cybershadow Apr 30 '21 at 20:12

0 Answers0