0

I would add a rect on every first child of a node list.

I loop this list and add a rectangle every time

What is happening is that the rect is getting added only on the last element of the loop.

let rect : NodeList = this.synoptic.nativeElement.querySelectorAll("#stops g");
let rect2 = document.createElementNS('http://www.w3.org/2000/svg','rect');
rect2.setAttribute("fill","red");
rect2.setAttribute('x', '0');
rect2.setAttribute('y', '0');
rect2.setAttribute('height', '50');
rect2.setAttribute('width', '50');
rect.forEach((elm : Node) => {
  elm.insertBefore(rect2,elm.firstChild);
  console.log(elm)
})

Here an example

Thomas
  • 9,760
  • 1
  • 12
  • 22
infodev
  • 3,933
  • 13
  • 50
  • 115
  • 2
    yes, you're moving `rect2` around, `elm` by `elm`. If you want one rect per elm, you need to create one rect per elm. And not one for all of them. – Thomas Jul 08 '19 at 12:25
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Heretic Monkey Jul 08 '19 at 12:33

0 Answers0