Search code examples
javascriptappendchild

How does appenchild work in this calendar?


    for (var k = 1; k <= totalDay; k++) {
      var dayTd = document.createElement("td");
      var dayNum = document.createTextNode(k);
      dayTd.appendChild(dayNum);
      weekTr.appendChild(dayTd);
      if ((firstDay + k) % 7 == 0) {
        var weekTr = document.createElement("tr");
      }
      calendar.appendChild(weekTr);
    }

I'm new to JavaScript and try to make a calendar. I try to print days of month out and accidentally find the code write in that way works! Though it prints out the result successfully, I don't really understand how calendar.appendChild(weekTr) in this loop works. I suppose it should be placed outside the loop after saving seven tds in one tr in the loop and then saving it to the table, but it doesn't seem like that. Please refer the code below.

https://jsfiddle.net/cnymd6x5/


Solution

  • appendChild removes an element from where it is (if it is anywhere) and then puts it at the end of the thing you are appending it to.

    So this:

    1. Puts the TR at the end of the table (assuming it had been created before the loop and wasn't anywhere in the DOM already).
    2. Removes the TR from the end of the table, then puts it back in the same place
    3. Removes the TR from the end of the table, then puts it back in the same place
    4. Removes the TR from the end of the table, then puts it back in the same place
    5. Removes the TR from the end of the table, then puts it back in the same place
    6. Removes the TR from the end of the table, then puts it back in the same place
    7. Removes the TR from the end of the table, then puts it back in the same place

    … and then the loop ends.