skip to Main Content

I want to create HTML objects using JS native script. I hae a function, that paints some text and I want to optimize it.

When I use it, it must write some text in HTML using loop to make several different iterations but instead I found out that new loop does not make a new object in HTML but remakes previous.

    paintPrimary: (id, alias, country, date, content) => {
        let primaryArray = ['Alias', 'Country', 'Date', 'Description'];
        console.log(primaryArray);
        const $primary = document.createElement('div');
        $primary.className = 'teamHeaders';

        for (let primaryCounter = 0; primaryCounter < primaryArray.length; primaryCounter ++) {
            $primary.innerHTML = primaryArray[primaryCounter];
            document.getElementById(id).appendChild($primary);
        }
    }

I tried to use constructors but had no success. Was thinking of making a new variable for every iteration everytime, but I dont know how to do such a thing and havent found any info

2

Answers


  1. Create the element div inside the loop. In your case you are creating the div only once, so it is overwriting

    paintPrimary: (id, alias, country, date, content) => {
      let primaryArray = ['Alias', 'Country', 'Date', 'Description'];
      for (let primaryCounter = 0; primaryCounter < primaryArray.length; primaryCounter++) {
        // changed here
        const $primary = document.createElement('div'); 
        $primary.className = 'teamHeaders';
        $primary.innerHTML = primaryArray[primaryCounter];
        document.getElementById(id).appendChild($primary);
      }
    }
    
    Login or Signup to reply.
  2. Try this:

    paintPrimary: (id, alias, country, date, content) => {
        let primaryArray = ['Alias', 'Country', 'Date', 'Description'];
        console.log(primaryArray);
    
        for (let primaryCounter = 0; primaryCounter < primaryArray.length; primaryCounter++) {
            const $primary = document.createElement('div');
            $primary.className = 'teamHeaders';
            $primary.innerHTML = primaryArray[primaryCounter];
            document.getElementById(id).appendChild($primary);
        }
    }
    

    When you call paintPrimary multiple times, it will create separate sets of div elements for each call, rather than overwriting the previous content.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search