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;


    if (toggle === true){
      toggle = false;
    } else{
      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

Since the html for the h2 element updated after the the first click of the toggle, JQuery does not “see” the second link because it was created after the original search for the btnToggle class. On each click, you need to tell JQuery to start looking at the h2 element with class=“testClass” and then look for all the elements where class=“btnToggle”. This will cause JQuery to find anything added to the h2 element since the last time something was clicked.

You would do this by:

$(".testClass").on('click','.btnToggle', function(){
1 Like

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