DOM Manipulation – Add 3 new divs (possibly using Node.cloneNode?) after pressing a button

Context: I’m trying to create a button so that every time someone presses it, it adds 3 new divs (one for the Ativo (ativo = stock in English), one for Quota%, and another for Perda Potencial). I’m starting by simply adding the Ativo div first to try this out. Then, I created a valuePercentage variable that would take the amount of slices on the pie chart (amount of slices = amount of ativos divs) so that I can get the Quota% (the quota is essentially 100 divided by the number of Ativos. Initially, I have 5 fixed so each Ativo will be 20%. This % should be adjusted as the user presses the “Add stock” button. If the user adds 5 more ativos, this Quota% should be 10, etc).

Problem: The method to add divs that I’m using isn’t working and I was looking at using node.cloneNode, but I’d like to generate new ativo IDs and not clone them. Could we mix node.cloneNode with template literals and a for loop so that the 3 divs are cloned, but the index of each ativo is changed (from 1 to 15 for example?). I currently have ativo1, ativo2, ativo3, ativo4 and ativo 5, and when the user presses the button, it should add new divs with ids like ativo 6, ativo7, etc

    //https://www.youtube.com/watch?v=y17RuWkWdn8&ab_channel=WebDevSimplified 
            // usar este video para criar uma função que faça append de um novo div com atributos semelhantes aos outros para permitir ao usuario adicionar novos ativos com o cloque de um butao 
            let valuePercentage;

            ////////////////////////////////////////////////////////////////////////////////////
            //Get all the values for each stock input and the quota variation (as "Perda potencial" increases, Quota decreases by a ratio of 1:5 and vice-versa)
            let perda;



            ////////////////////////////////////////////////////////////////////////////////////
            //Load google chart graphs

            google.charts.load("current", { packages: ["corechart"] });
            google.charts.setOnLoadCallback(drawChart);

            //This value percentage is essentially the "Quota". This value will be 100% divided by the amount of slices (essentialy, divided by ativo1, ativo2, ativo3... ativo(i))


            // Function that will add new "Ativo", a new "Quota%" and a new "Perda potencial%". 
            function addStock() {
                for (let i = 6; i <= 15; i++) {
                    let input = document.getElementById(`ativo${i}`).value;
                    input = input.length + 1;
                    document.getElementbyId(`field_div`).innerHTML = document.getElementbyId(`field_div`).innerHTML + `
                    <div class="td" id="field_div"><input type="text" size="5" value="${input}" class="stock" id="ativo${i}"
                            onchange="drawChart();" /> </div>`
                }
            }

            //Function that removes the divs added
            // function removeStock(id) {

            //  for (let i = 6; i <= 10; i++) {
            //      document.getElementById(`ativo${i}`).innerHTML = "";
            //  }
            // }

            //1º Get the lenght, 2º get the IDs
            // let ativoArray;
            // for (let i = 1; i <= 15; i++) { // cap the max amount of ativos at 15
            //  ativoArray = document.getElementById(`ativo${i}`)
            //  //console.log(ativoArray)
            // }

            ////////////////////////////////////////////////////////////////////////////////////
            //Function that will be passed by the "Draw Graph" button so that everytime the user clicks the button, it takes the new input values and updates the pie chart
            function drawChart() {
                const slices = [];
                for (let i = 1; i <= 5; i++) {
                    slices.push({
                        ativo: document.getElementById(`ativo${i}`).value,
                        quota: parseFloat(document.getElementById(`quota${i}`).value)
                    })
                }
                valuePercentage = (100 / slices.length);

                //Calculate the Loss (Perda) 
                let sum = 0.0;
                for (let i = 0; i < slices.length; i++) {
                    sum += slices[i].quota;
                };
                perda = 100.0 - sum;

                //Create data table with input data
                var data = new google.visualization.DataTable();
                data.addColumn("string", "Ativo");
                data.addColumn("number", "Quota");
                data.addRows([
                    ...slices.map(slice => ([slice.ativo, slice.quota])),
                    ["Perda", perda],
                ]);

                //Styling
                let options = {
                    'legend': 'right',
                    pieHole: 0.3,
                    pieSliceText: 'value',
                    is3D: true,
                    colors: ['#FBB117', '#6AA121', '#728FCE', '#4863A0', '#7D0552', '#FF0000'],
                    backgroundColor: '#DFCFBE',
                    chartArea: {
                        left: 50,
                        right: 50,
                        top: 70
                    }
                };

                var chart = new google.visualization.PieChart(
                    document.getElementById("piechart")
                );

                chart.draw(data, options);

            }
            document.querySelector(".row").addEventListener("input", function (e) {
                const tgt = e.target;
                if (tgt.classList.contains("perda")) {
                    perda = Number(tgt.closest(".tr").querySelector(".quota").value =
                        valuePercentage - tgt.value * 0.2) //O 20 será alterado para a expressao de numero de quotas a dividir por 100%

                    //console.log(perda)
                    // quota * perda potencial; var = quota * +- perda potencial / 100
                    //quota - var;
                    //let var = perda/risco potencial
                    //console.log(20 - perda);

                    //isto teria que atualizar sempre que a perda potencial % aumenta ou diminui. Neste momento, apenas faz a soma, nao retira o valor quando perda potencial % diminui e a quota aumenta
                }
            });
            ////////////////////////////////////////////////////////////////////////////////////
{
        box-sizing: content-box;
    }

    /* Set additional styling options for the columns */
    .column {
        float: left;
    }

    /* Set width length for the left, right and middle columns */
    .left {
        width: 30%;
    }

    .right {
        width: 80%;
    }

    .row:after {
        content: "";
        display: table;
        clear: both;
        height: 100%;
    }

    .td {
        display: inline-block;
        width: 120px;
        text-align: center;
        font-family: 'Trebuchet MS', sans-serif;
    }

    .tr {
        font-family: 'Trebuchet MS', sans-serif;
    }

    .button1 {

        width: 20%;
        margin-left: 35%;
        margin-right: 25%;
        margin-top: 10px;
        font-family: 'Trebuchet MS', sans-serif;

    }

    .button2 {

        width: 20%;
        margin-left: 35%;
        margin-right: 25%;
        margin-top: 10px;
        font-family: 'Trebuchet MS', sans-serif;

    }

    .piechart {
        width: 100%;
        height: 100%;
    }
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

</head>

<body style="background-color:#DFCFBE">

    <div class="row">
        <div class="column left">
            <form id=" form">

                <div class="tr">
                    <div class="td">Ativo </div>
                    <div class="td">Quota % </div>
                    <div class="td">Perda Potencial % </div>
                </div>
                <div class="tr" id="wrapper">
                    <div class="td" id="field_div"><input type="text" size="5" value="TSLA" class="stock" id="ativo1"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota1"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda1" />
                    </div>
                </div>
                <div class="tr" id="wrapper">
                    <div class="td" id="field_div"><input type="text" size="5" value="AAPL" class="stock" id="ativo2"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota2"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda2" />
                    </div>
                </div>
                <div class="tr" id="wrapper">
                    <div class="td" id="field_div"><input type="text" size="5" value="MSFT" class="stock" id="ativo3"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota3"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda3" />
                    </div>
                </div>
                <div class="tr" id="wrapper">
                    <div class="td" id="field_div"><input type="text" size="5" value="EURUSD" class="stock"
                            id="ativo4" />
                    </div>
                    <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota4" />
                    </div>
                    <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda4" />
                    </div>
                </div>
                <div class="tr" id="wrapper">
                    <div class="td" id="field_div"><input type="text" size="5" value="BITCOIN" class="stock" id="ativo5"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota5"
                            onchange="drawChart();" /> </div>
                    <div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda5" />
                    </div>
                </div>
                <button class="button2" type="button" onclick="addStock();">Add Stock</button>
                <button class="button1" type="button" onclick="drawChart();">Draw Graph</button>


            </form>
        </div>

        <div class="column right" style="position:relative;width:70%">
            <div class=" piechart" id="piechart" style="position:absolute;right:0px;top:0px;width: 900; height: 590px;">
            </div>

        </div>
</body>

Answer

So, first of all like i did mentioned in the comments, you use multiple identifiers attributes, this is not html5 valid. Identifier attributes need to be unique, about performance etc.., not reason why you post.

I did change you html and used data attributes, we create a Wrapper that we define with data-type="wrapper". We stored the index inside of the html by using another data attribute data-index="1". beware data attributes are slower then storing your data in javascript, but for this small script you will not have any gain by doing so.

We use some dom traversal to get the right elements we want. Also i did change your html with the button onclick="addStock(event);" this was because i like to use the event.currentTarget and event.target properties to have more control about my code instead of using this.

In the example below you can have an idea how to future improve your code. deleting like you said you were trying is now kinda easy.

If you have more questions, feel free to comment.

Code;

function addStock(event) {

  // find the last Wrapper [data-set="wrapper"]
  let lastWrapper = event.currentTarget.form.querySelector(`[data-type="wrapper"]:last-of-type`);
  // get the index of the last Wrapper
  let lastIndex = lastWrapper.dataset.index;
  
  //not more then 15
  if ( lastIndex < 15 ) {
  
      //clone the wrapper
      let clonerNode = lastWrapper.cloneNode(true);
  
      //change index of cloner Wrapper
      clonerNode.dataset.index = parseInt(lastIndex, 10) + 1;
  
      //changes values;
      clonerNode.querySelector(`.stock`).value = "NEW STOCK";
      clonerNode.querySelector(`.quota`).value = 0;
  
      //append clonernode after lastWrapper
      lastWrapper.insertAdjacentElement('afterend', clonerNode);      
}

//https://www.youtube.com/watch?v=y17RuWkWdn8&ab_channel=WebDevSimplified 
// usar este video para criar uma função que faça append de um novo div com atributos semelhantes aos outros para permitir ao usuario adicionar novos ativos com o cloque de um butao 
let valuePercentage;

////////////////////////////////////////////////////////////////////////////////////
//Get all the values for each stock input and the quota variation (as "Perda potencial" increases, Quota decreases by a ratio of 1:5 and vice-versa)
let perda;



////////////////////////////////////////////////////////////////////////////////////
//Load google chart graphs

google.charts.load("current", {
  packages: ["corechart"]
});
google.charts.setOnLoadCallback(drawChart);

//This value percentage is essentially the "Quota". This value will be 100% divided by the amount of slices (essentialy, divided by ativo1, ativo2, ativo3... ativo(i))


// Function that will add new "Ativo", a new "Quota%" and a new "Perda potencial%". 
function addStock(event) {

  // find the last Wrapper [data-set="wrapper"]
  let lastWrapper = event.currentTarget.form.querySelector(`[data-type="wrapper"]:last-of-type`);
  // get the index of the last Wrapper
  let lastIndex = lastWrapper.dataset.index;
  
  //not more then 15
  if ( lastIndex < 15 ) {
  
  //clone the wrapper
  let clonerNode = lastWrapper.cloneNode(true);
  
  //change index of cloner Wrapper
  clonerNode.dataset.index = parseInt(lastIndex, 10) + 1;
  
  //changes values;
  clonerNode.querySelector(`.stock`).value = "NEW STOCK";
  clonerNode.querySelector(`.quota`).value = 0;
  
  //append clonernode after lastWrapper
  lastWrapper.insertAdjacentElement('afterend', clonerNode);
  
  
  
  
   }

  console.log(lastIndex);

}

//Function that removes the divs added
// function removeStock(id) {

//  for (let i = 6; i <= 10; i++) {
//      document.getElementById(`ativo${i}`).innerHTML = "";
//  }
// }

//1º Get the lenght, 2º get the IDs
// let ativoArray;
// for (let i = 1; i <= 15; i++) { // cap the max amount of ativos at 15
//  ativoArray = document.getElementById(`ativo${i}`)
//  //console.log(ativoArray)
// }

////////////////////////////////////////////////////////////////////////////////////
//Function that will be passed by the "Draw Graph" button so that everytime the user clicks the button, it takes the new input values and updates the pie chart
function drawChart() {
  const slices = [];
  for (let i = 1; i <= 5; i++) {
//    slices.push({
//      ativo: document.getElementById(`ativo${i}`).value,
//      quota: parseFloat(document.getElementById(`quota${i}`).value)
//    })
  slices.push({
     ativo: document.querySelector(`div [data-type="wrapper"][data-index="${i}"] .stock`).value,
     quota: parseFloat(document.querySelector(`div [data-type="wrapper"][data-index="${i}"] .quota`).value)
   })


  }
  valuePercentage = (100 / slices.length);

  //Calculate the Loss (Perda) 
  let sum = 0.0;
  for (let i = 0; i < slices.length; i++) {
    sum += slices[i].quota;
  };
  perda = 100.0 - sum;

  //Create data table with input data
  var data = new google.visualization.DataTable();
  data.addColumn("string", "Ativo");
  data.addColumn("number", "Quota");
  data.addRows([
    ...slices.map(slice => ([slice.ativo, slice.quota])), ["Perda", perda],
  ]);

  //Styling
  let options = {
    'legend': 'right',
    pieHole: 0.3,
    pieSliceText: 'value',
    is3D: true,
    colors: ['#FBB117', '#6AA121', '#728FCE', '#4863A0', '#7D0552', '#FF0000'],
    backgroundColor: '#DFCFBE',
    chartArea: {
      left: 50,
      right: 50,
      top: 70
    }
  };

  var chart = new google.visualization.PieChart(
    document.getElementById("piechart")
  );

  chart.draw(data, options);

}
document.querySelector(".row").addEventListener("input", function(e) {
  const tgt = e.target;
  if (tgt.classList.contains("perda")) {
    perda = Number(tgt.closest(".tr").querySelector(".quota").value =
      valuePercentage - tgt.value * 0.2) //O 20 será alterado para a expressao de numero de quotas a dividir por 100%

    //console.log(perda)
    // quota * perda potencial; var = quota * +- perda potencial / 100
    //quota - var;
    //let var = perda/risco potencial
    //console.log(20 - perda);

    //isto teria que atualizar sempre que a perda potencial % aumenta ou diminui. Neste momento, apenas faz a soma, nao retira o valor quando perda potencial % diminui e a quota aumenta
  }
});
////////////////////////////////////////////////////////////////////////////////////
{
        box-sizing: content-box;
    }

    /* Set additional styling options for the columns */
    .column {
        float: left;
    }

    /* Set width length for the left, right and middle columns */
    .left {
        width: 30%;
    }

    .right {
        width: 80%;
    }

    .row:after {
        content: "";
        display: table;
        clear: both;
        height: 100%;
    }

    .td {
        display: inline-block;
        width: 120px;
        text-align: center;
        font-family: 'Trebuchet MS', sans-serif;
    }

    .tr {
        font-family: 'Trebuchet MS', sans-serif;
    }

    .button1 {

        width: 20%;
        margin-left: 35%;
        margin-right: 25%;
        margin-top: 10px;
        font-family: 'Trebuchet MS', sans-serif;

    }

    .button2 {

        width: 20%;
        margin-left: 35%;
        margin-right: 25%;
        margin-top: 10px;
        font-family: 'Trebuchet MS', sans-serif;

    }

    .piechart {
        width: 100%;
        height: 100%;
    }
<script src="https://www.gstatic.com/charts/loader.js"></script>
<body style="background-color:#DFCFBE">

  <div class="row">
    <div class="column left">
      <form id=" form">

        <div class="tr">
          <div class="td">Ativo </div>
          <div class="td">Quota % </div>
          <div class="td">Perda Potencial % </div>
        </div>
        <div class="tr" data-type="wrapper" data-index="1">
          <div class="td" data-type="field_div"><input type="text" size="5" value="TSLA" class="stock" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="20" value="20" class="quota" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="100" value="0" class="perda" />
          </div>
        </div>
        <div class="tr" data-type="wrapper" data-index="2">
          <div class="td" data-type="field_div"><input type="text" size="5" value="AAPL" class="stock" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="20" value="20" class="quota" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="100" value="0" class="perda" />
          </div>
        </div>
        <div class="tr" data-type="wrapper" data-index="3">
          <div class="td" data-type="field_div"><input type="text" size="5" value="MSFT" class="stock" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="20" value="20" class="quota" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="100" value="0" class="perda" />
          </div>
        </div>
        <div class="tr" data-type="wrapper" data-index="4">
          <div class="td" data-type="field_div"><input type="text" size="5" value="EURUSD" class="stock" />
          </div>
          <div class="td"><input type="number" min="0" max="20" value="20" class="quota" />
          </div>
          <div class="td"><input type="number" min="0" max="100" value="0" class="perda" />
          </div>
        </div>
        <div class="tr" data-type="wrapper" data-index="5">
          <div class="td" data-type="field_div"><input type="text" size="5" value="BITCOIN" class="stock" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="20" value="20" class="quota" onchange="drawChart();" /> </div>
          <div class="td"><input type="number" min="0" max="100" value="0" class="perda" />
          </div>
        </div>
        <button class="button2" type="button" onclick="addStock(event);">Add Stock</button>
        <button class="button1" type="button" onclick="drawChart();">Draw Graph</button>


      </form>
    </div>

    <div class="column right" style="position:relative;width:70%">
      <div class=" piechart" id="piechart" style="position:absolute;right:0px;top:0px;width: 900; height: 590px;">
      </div>

    </div>
</body>