Adding html tags with javaScript

I am trying to make a toggle switch for the Local Weather project and I ran into an issue regarding javaScript/jQuery.

I have simplified my js code here and my html has only an h2 with .testClass class.

So I’d like the sum number to change whenever I click on sum1/sum2 text. While it works once (clicking on sum1 text changes to sum2), it doesn’t work the second time (else statement).
Also, if I remove the anchor tags from the sum1, sum2 variables and keep the text only, then target .testClass instead of .btnToggle, it seems to work but the click event is on the entire h2 .testClass

Is is common practice to add html tags with js? What am I missing here?

  var sum1 = 32 + " <a href='#' class='btnToggle'> Sum 1</a>";
  var sum2 = 88 + " <a href='#' class='btnToggle'> Sum 2</a>";
  var toggle = true;

  $(".testClass").html(sum1);

  $(".btnToggle").click(function(){
    if (toggle === true){
      $(".testClass").html(sum2);
      toggle = false;
    } else{
      $(".testClass").html(sum1);
      toggle = true;
    }
  });

Thanks to anyone who has the patience to answer my question!

By changing the html to the value of sum1 or sum2 you are stripping out all the other information in the original html - including the class.

So after the first click, the DOM Node you are targeting no longer exists!

You could either manually recreate the HTML as the value of your variables: <p class='testClass'>33</p>, or try the .text() method instead of .html().

1 Like

Thanks! This answered my question. It’s complicated the way jQuery sees/doesn’t see things created in html after/before events.