0

var input = document.getElementById("userinput");
var button = document.getElementById("button");

var ul = document.querySelector("ul");



button.addEventListener("click", function() {

  var li = document.createElement('li');
  li.textContent = input.value;
  ul.appendChild(li);
  input.value = "";


  liarray = document.querySelectorAll("li");

  li.addEventListener("click", function() {
    liarray.pop();

  })
})

When I'm running and clicking on an li element, I get an "Uncaught TypeError: liarray.pop is not a function" error message.

Any help? Thanks

Run_Script
  • 2,487
  • 2
  • 15
  • 30
  • 1
    `querySelectorAll` does not return an `Array`. `pop` is an array method – Taplar May 13 '20 at 15:22
  • `liarray = [ ...document.querySelectorAll("li") ];` It is array now. – palaѕн May 13 '20 at 15:25
  • @EugenSunic - Yeah -- and they probably don't want `liarray` at all at that point (but if they do, they'll *also* want to remove it from there, since `NodeList`s aren't live collections like `HTMLCollection`s are). – T.J. Crowder May 13 '20 at 15:27

1 Answers1

0

querySelectorAll doesn't return an array, it returns a NodeList. NodeLists don't have a pop method.

If you want an array:

liarray = Array.from(document.querySelectorAll("li"));

...or any of several similar things, for instance:

liarray = [...document.querySelectorAll("li")];

...but note that that relies on the NodeList being iterable, and they were only made iterable in the last year or two, so it relies on a fairly up-to-date browser. Array.from is older (and easily polyfilled).


That said, looking at your code, I don't think you want liarray at all, and I don't think you want pop. It looks like you want to remove an element on click. If so:

var input = document.getElementById("userinput");
var button = document.getElementById("button");

var ul = document.querySelector("ul");

button.addEventListener("click", function(){
    var li = document.createElement('li');
    li.textContent=input.value;
    ul.appendChild(li);
    input.value = "";
    li.addEventListener("click", function(){
        this.remove(); // Or `this.parentElement.removeChild(this);` on older browsers
    });
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875