Anh Nguyễn Thế
Anh Nguyễn Thế

Reputation: 25

append() "<tr> element" twenty-five times to the "<table> element" But the <table> only have 1 row when running HTML

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>

Upvotes: 2

Views: 50

Answers (2)

fdomn-m
fdomn-m

Reputation: 28611

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):

Upvotes: 1

Gentjan Likaj
Gentjan Likaj

Reputation: 11

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

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

Upvotes: 1

Related Questions