0

I have a module where I have an object and I append some elements depending how long is that object. Now I want to set different ID's for all elements.

Here's my code:

Items.map(item =>{

var ParentDiv = document.getElementById('parentDiv');
var headerH1 = document.createElement('h1')
headerH1.setAttribute('id','header1')
ParentDiv.appendChild(headerH1);

})

What I have tried:

for(var i=0;i<=50;i++)
{
    headerH1.setAttribute('id','header'+i)
    ParentDiv.appendChild(headerH1);
}

I thought this would work but it just appends 50 elements but their ID will all be the same, "header50".

Can you tell me what am I missing me? Much appreciated.

LeotrimR
  • 62
  • 6
  • 1
    To solve the issue in your question, you need to call `createElement()` ***within*** your loop, other wise you just create 1 element and clone it 50 times while updating the reference to it. However, more importantly, *never* use `id` attributes for repeated content. Use a common `class` which is the same for all generated elements. You can target them using DOM traversal methods based on the element which raises the required event handler. – Rory McCrossan Jan 17 '23 at 20:43
  • 2
    To simply state it. You are only creating one node and moving it around by calling `appendChild`. – Ruan Mendes Jan 17 '23 at 20:48

1 Answers1

1

Each createElement represents its own DOM element, and you need to interact with each element independently:

const parentDiv = document.getElementById('parentDiv');

Items.forEach((item, i) => {
  const newItem = document.createElement('h1');
  newItem.setAttribute('id', `header${i}`);
  parentDiv.appendChild(newItem);
});

Also, while not required, I switched your map to a forEach since map should really only be used to create a new list, not as a function to just iterate over a list, which is what forEach is for.

Also, it's 2023, use let/const instead of var :)

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128