skip to Main Content

Can anyone explain why this loop in "code1" does’nt add 25 -Elements to the table? (Iam very newbie)

The code that only have 1 row in the table here (code1):
https://jsfiddle.net/yuLr3p6s/2/

alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

let tr = $("<tr></tr>"); // create tr Element with Jquery
for (let i = 0; i < alphabet.length; i++) {

  let td = "<td>" + alphabet[i] + "</td>";
  tr.append(td);
}


/* append tr Element to the end of Table element twenty-five times
and table will have twenty five rows*/
for (let i = 1; i <= 25; i++) {
  $("table").append(tr);
}
table, td {
    border: 1px solid black;
    border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="myDiv">
  <table>

  </table>
</div>

The code that have 25 rows in the table here (code2):
https://jsfiddle.net/yuLr3p6s/1/

alphabet = ["A","B","C","D","E","F","G","H","I","J","K"        ,"L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

let tr = "<tr>"; // create tr Element with Jquery
for (let i = 0 ; i < alphabet.length ; i++) { 
    
    let td = "<td>" + alphabet[i] + "</td>";
    tr += td;
}
tr += "</tr>";


/* append tr Element to the end of Table element twenty-five times
and table will have twenty five rows*/
for (let i = 1; i <= 25 ; i++) {     
    $("table").append(tr);
}
table, td {
    border: 1px solid black;
    border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv">
        <table>

        </table>
</div>

2

Answers


  1. You are inserting inside one row
    try put inside the loop :

    let td = "" + alphabet[i] + "";

    Login or Signup to reply.
  2. Your code:

    let tr = $("<tr></tr>");
    

    create a DOM node, while

    let tr = "<tr>";
    

    creates a string.

    When you use jquery methods such as .append() and .appendTo() on DOM nodes, jquery will move that node rather than create new ones.

    The same methods with a string will create new nodes; which is why it works in your second snippet.

    TBH, it’s not that clear from the jquery documentation, there’s a small line about half-way down:

    https://api.jquery.com/append/

    If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned):

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