Changing an element's outerHTML removes it from array

Viewed 73

Consider the following snippet:

var cites = document.getElementsByTagName('cite');
console.log(cites.length);
cites[0].outerHTML = "[" + cites[0].innerText + "]";
console.log(cites.length);
<cite>ASDF</cite>
<cite>FDSA</cite>

The two console.log calls print different values (2 and 1 respectively), because the first element of the array gets removed from the array when assigning to its outerHTML property. Why is this?

1 Answers

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically. https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName

So after you changed outerHTML, you changed the tag itself and was not more “cite”

Related