Search code examples
javascripthtml-lists

getting the length of an array of elements when the number can change (adding or removing elements)


So I don't have code for the question but Im curious to know if i wanted to create a ul of li's and want to add and remove the li's, I know the number of li's will be dynamic. So how do I get the number of li's (array indexes) when its adding or removing. I have tried doing const len = document.querySelectorAll("li") and this will only return the length of the array static, if I add or remove li's it wont change the length of the array


Solution

  • document.getElementsByTagName("li") returns a live HTMLCollection, so its length should always be up-to-date. https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName