简体   繁体   中英

How to sum elements dynamically added with Javascript?

I am adding table rows dynamically to a table using Javascript.

Is there a reason why items.length doesn't increase when I add a row?

I am also trying to sum the numbers contained in each row. But this doesn't work either. The dynamically added rows are completely ignored for some reason.

I am coming from jQuery where things like these used to work.

I am probably missing something really fundamental here. Thanks for any pointers.

document.addEventListener("DOMContentLoaded", function() {

  var form = document.querySelector("#form");
  var items = form.querySelectorAll(".item");

  form.addEventListener("click", function(event) {
    if (event.target.className == ".add_item") {
      addFields(event);
    }
  });

  function addFields(event) {
    var item = document.createElement("template");
    item.innerHTML = fields.trim();
    items[items.length - 1].insertAdjacentElement("afterend", item.content.firstChild);
    console.log(items.length);
    event.preventDefault();
  }

})

querySelector and querySelectorAll returns NodeList where as getElementsByClassName returns HTMLCollection .

The difference is, NodeList is a static copy but HTMLCollection is a live copy. So if element is modified, like in your case, a new row is added, HTMLCollection will work but NodeList will not.

So changing

var items = form.querySelectorAll(".item")

to

var items = form.getElementsByClassName("item")

might solve the problem.

Pointers

  • You cannot have a selector in getElementsByClassName . It expects a className, you cannot use composite selector like #form.item .

Reference:

You only query the items once here:

var items = form.querySelectorAll(".item");

form.addEventListener(
  //you call addItem here
)

function addItem(){
  //you access items.length here
}

You need to keep re-query-ing the selectors every time you add an item.

var items = form.querySelectorAll(".item"); //i got queried for the 1st time

function addFields(event) {
  items = form.querySelectorAll(".item"); //get items again

  //...
}

Or just don't query outside addFields() all in all. Put var items =... in the function. There's no need to put it outside.

Read up @Rajesh's answer why this is so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM