user672518
user672518

Reputation: 95

Button on click declared in js doesn't work

I am trying to create a new p tag after the button is clicked yet nothing happens after it's clicked:

(function() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 403) {
      var heading = document.getElementById("head");
      var para = document.createElement("P");
      para.innerHTML = "Accept the T&Cs to Continue";
      var button = document.createElement("BUTTON"); // button created here
      button.classList.add("theButton");
      var theButton = document.getElementsByClassName("theButton");
      theButton.onclick = function() { // button doesn't work onclick
        var newP = document.createElement("P");
        newP.innerHTML = "DONE";
        heading.appendChild(newP);
        heading.appendChild(para);
        heading.appendChild(button);
      };
    }
  };
  xhttp.open("GET", "/content.ajax", true);
  xhttp.send();
})();

Can someone help me with this?

Upvotes: 0

Views: 45

Answers (1)

ItsFlo
ItsFlo

Reputation: 103

I´m assuming that document.getElementsByClassName("theButton") should get your button, because it uses the same class.

  1. That´s unnecessary because you already have a reference to your button.
  2. Your button (and para) did not get attached to the DOM, so getElementsByClassName would return an empty result.
  3. document.getElementsByClassName() returns a HTMLCollection (a list), not a single element. You can´t add a listener function to a HTMLCollection.
  4. The button only gets added to the DOM when it is clicked. But you can only click it after it got added to the DOM.

Also you should consider using addEventListener because your listener can´t be overwritten that way and you can add multiple listeners.

(function () {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if(this.readyState ==4 && this.status == 403){
            var heading = document.getElementById("head");
            var para = document.createElement("P");
            para.innerHTML = "Accept the T&Cs to Continue";

            var button = document.createElement("BUTTON"); // button created here
            button.classList.add("theButton");
            button.addEventListener("click", function() {
                var newP = document.createElement("P");
                newP.innerHTML = "DONE";
                heading.appendChild(newP);
            });

            heading.appendChild(para);
            heading.appendChild(button);
        }
    };
    xhttp.open("GET","/content.ajax",true);
    xhttp.send();
})();

Upvotes: 1

Related Questions