Search code examples
javascriptarraysfor-loopif-statementinnerhtml

Display fraction of innerHTML output on every odd/second loop?


Quite new to Stack Overflow and new enough to javascript also.
Hope the issue is not to unclear on my behalf for people to understand.

I have an issue where I have a for loop which displays my content on every loop and that was the way I needed it to display initially, it was also in the perfect format for display.

I now have an issue where I want one part of my innerHTML output 'myArr[i]' to only display on every odd loop and not on the even loops while the rest still displays on every loop...

Any suggestions?

var clicks = 0;
document.getElementById("arrowLink").innerHTML.value = clicks; // clickable arrow

document.getElementById("arrowLink").addEventListener("click", function()
  {
  if (clicks < 1)
    {
    for(var i=0; i < displayArr1.length; i++)
      {
      middleEndpoints.innerHTML +=
        "<div class='d-flex justify-content-center'>"+
          "<div class='p-2'>"+
              "<p>Abc</p>"+
          "</div>"+
        
// HOW DO I GET THE BELOW PART OF MY CODE TO ONLY DISPLAY ON EVERY ODD OR SECOND LOOP?
 
        "<div class='row'>"+
          "<div class='col-sm-1 align-self-center'>"+
            "<p style='margin-bottom: 0;'>" + myArr[i] + "</p>"+
          "</div>"+

//----------------------------------------------------------------------------

          "<div class='col-sm-10 align-self-center'>"+
            "<p class='midLine'>&#8645;</p>"+
          "</div>"+
        "</div>"; 
      }
      clicks += 1;
    }
  });

Solution

  • Perhaps this?

    document.getElementById("arrowLink").addEventListener("click", function() {
      if (clicks >= 1) return
      clicks++;
      const html = [];
      displayArr1.forEach((item, i) => {
        html.push(`<div class='d-flex justify-content-center'>
            <div class='p-2'>
            <p>Abc</p>
            </div>`);
        if (i % 2) {
          html.push(`<div class='row'>
                <div class='col-sm-1 align-self-center'>
                <p style='margin-bottom: 0;'>${myArr[i]}</p>
                </div>`);
        }
        html.push(`<div class='col-sm-10 align-self-center'>
            <p class='midLine'>&#8645;</p>
            </div>
            </div>`)
      });
      middleEndpoints.innerHTML=html.join("");
      clicks += 1;
    });