1

How to make HTMLCollection not live?

var cells = someTable.getElementsByTagName('td');

Is live collection, meaning that when I add new td to table, cells length will increase by 1. How can I make it not live?

asdjfiasd
  • 1,572
  • 15
  • 28

1 Answers1

1

You have a couple of options.

One is to use querySelectorAll instead; it returns a "snapshot" NodeList:

var cells = someTable.querySelectorAll("td");

Another option is to convert it into an array:

var cells = Array.from(someTable.getElementsByTagName("td"));

Array.from is relatively new, but can be polyfilled for older browsers. Or if you want to support old browsers without polyfilling, use slice:

var cells = Array.prototype.slice.call(someTable.getElementsByTagName("td"));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875