Na stronie: innerHTML

Praktyka: kalendarz - JavaScript od podstaw: konsola (HTML/CSS/JS)

Ten sam kod, tylko wynik nie idzie do konsoli, lecz do strony. Na stronie jest pusty `<div id="calendar">`. Skrypt na końcu `<body>` znajduje go `document.getElementById` i wpisuje do `innerHTML` napis z kodem tabeli: przeglądarka zamienia go na elementy. To najszybszy sposób, ale ma wady: każda zmiana przebudowuje całą zawartość, a wstawianie tekstu od użytkownika do `innerHTML` jest niebezpieczne (mógłby wstrzyknąć własny kod).

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <title>Kalendarz: innerHTML</title>
  <style>
    table { border-collapse: collapse; font-family: sans-serif; }
    th, td { border: 1px solid #94a3b8; width: 2.5em; height: 2em; text-align: center; }
    th { background: #e0e7ff; color: #1e1b4b; }
  </style>
</head>
<body>
  <h1>Listopad 2026</h1>
  <div id="calendar"></div>
  <script>
    function buildWeeks(year, month) {
      const first = (new Date(year, month - 1, 1).getDay() + 6) % 7;
      const days = new Date(year, month, 0).getDate();
      const cells = [];
      for (let i = 0; i < first; i++) cells.push(null);
      for (let d = 1; d <= days; d++) cells.push(d);
      while (cells.length % 7 !== 0) cells.push(null);
      const weeks = [];
      for (let i = 0; i < cells.length; i += 7) {
        weeks.push(cells.slice(i, i + 7));
      }
      return weeks;
    }
    function renderHtml(weeks) {
      let html = '<table>';
      html += '<tr><th>Pn</th><th>Wt</th><th>Śr</th><th>Cz</th><th>Pt</th><th>So</th><th>Nd</th></tr>';
      for (const week of weeks) {
        const cells = week.map(day => `<td>${day === null ? '' : day}</td>`);
        html += '<tr>' + cells.join('') + '</tr>';
      }
      return html + '</table>';
    }

    document.getElementById('calendar').innerHTML = renderHtml(buildWeeks(2026, 11));
  </script>
</body>
</html>

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu JavaScript od podstaw: konsola·Zaloguj się, aby zapisać postęp na koncie.