0

I have simple question regarding table row.

Below is the example:

var data = ['A', 'B', 'C', 'D', 'E'];

for(var i=0; i<data.length; i++) {
  var element = `
    <td>${i}</td><tr>
  `;
  
  console.log(element);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The result from console.log is:

<td>0</td><tr>
<td>1</td><tr>
<td>2</td><tr>
<td>3</td><tr>
<td>4</td><tr>

Now I need at the last row <td>4</td><tr> no need this <tr>. It should be like this <td>4</td>.

Is there any trick to handle it?

HiDayurie Dave
  • 1,791
  • 2
  • 17
  • 45
  • 3
    This HTML does not make sense. It is highly invalid. Can you please post the required end result? – mplungjan Jan 19 '23 at 10:17
  • Hi, before going to result, I need to make sure first on variable `element` last row is not added `tr` – HiDayurie Dave Jan 19 '23 at 10:20
  • 1
    Why are you adding a `` opening tag after a ``, and never closing any of the opened rows? (The closing tag [is optional](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr#technical_summary), but the way you're constructing your HTML is confusing at best). – David Thomas Jan 19 '23 at 10:27

1 Answers1

1

You can try this:


for(let i=0; i<data.length; i++) {
  let element = `<td>${i}</td>`;
  if (i !== data.length-1) {
    element += "<tr>";
  }
  console.log(element);
}
FaFa
  • 358
  • 2
  • 16