Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript add new row with <tr> then remove at the last row

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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?

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading