0

I have a page with most of the content generated from an XML file. The generated content is a table with the first cell in each row being an expanding element:

<details><summary>...</summary>...</details>

I’m trying to change the content of some <summary> into links as they are being generated. The content of the <summary> may be text or an <img> and text. Since appendChild doesn’t allow me to append a NodeList, my alternative for this was to cycle through the <summary> children and add them to the link, then append the link to a replacement <summary>. Unfortunately, the for loop never accessed the second child.

for (var j = 0; j < curSummary.childNodes.length; j++) {
  // ...
}

I verified that curSummary.childNodes.length is actually 2 but the loop only ever executed once for each <summary>. Putting an alert in to display the value of the loop variable showed it was only ever 0.

alert('there are' + curSummary.childNodes.length + ' nodes');

for (var j = 0; j < curSummary.childNodes.length; j++) { 
  alert('appending child node ' + j + ' of ' + curSummary.childNodes.length);
}

Apart from omitting the text, the code worked. The summary showed up with <img> as a link. Just to be clear, both the image and text are displayed when there isn’t a link.

And no, I’m not changing the value of the loop variable nor issuing a “break” anywhere in the loop.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Gary Dale
  • 79
  • 9
  • [I can't reproduce that](https://jsfiddle.net/x3fmra7d/). Please provide a [mcve]. – Ivar Mar 17 '22 at 22:42
  • [`childNodes`](//developer.mozilla.org/en/docs/Web/API/Node/childNodes) is a _live_ collection. If you append these nodes elsewhere, they disappear from the `NodeList` _as you’re iterating_. Related: [Strange behavior when iterating over HTMLCollection from getElementsByClassName](/q/15562484/4642212). Technically a dupe of [AppendChild in for loop adds every second child?](/q/69677367/4642212), but the answer isn’t very good at explaining why this happens. – Sebastian Simon Mar 17 '22 at 23:26
  • Tangentially related to [What do querySelectorAll and getElementsBy\* methods return?](/q/10693845/4642212) (see solution in answer). – Sebastian Simon Mar 17 '22 at 23:31
  • So I should be iterating through appending the firstChild until childNodes == 0. Thanks Sebastian. – Gary Dale Mar 18 '22 at 00:31

0 Answers0