Skip to content

DOM i jego znaczenie

This content is not available in your language yet.

DOM (Document Object Model) to interfejs programistyczny reprezentujacy strukture dokumentu HTML jako drzewo obiektow. Dzieki DOM, JavaScript może dynamicznie modyfikować zawartosc, strukture i style strony internetowej.

Każdy element HTML staje się obiektem (węzłem), który można odczytywać, modyfikować lub usuwać za pomoca JavaScript. DOM stanowi most miedzy statycznym kodem HTML a dynamicznymi interakcjami na stronie.

  • Nie jest czescia JavaScript - to API przegladarki
  • Nie jest tym samym co HTML - HTML to tekst, DOM to obiektowa reprezentacja
  • Jest dynamiczny - zmiany w DOM natychmiast widac na stronie
  • Element - tag HTML (div, p, span)
  • Text - tekst wewnatrz elementu
  • Attribute - atrybut elementu (class, id)
  • Document - korzen drzewa DOM
  • Comment - komentarz HTML
document
<html>
/ \
<head> <body>
│ / \
<title> <div> <footer>
<p>
/ \
"Tekst" <span>

Przykładowy HTML:

<!DOCTYPE html>
<html>
<head>
<title>Strona</title>
</head>
<body>
<div id="container">
<p class="text">Tekst <span>ważny</span></p>
</div>
<footer>Stopka</footer>
</body>
</html>
// Po ID - zwraca jeden element lub null
const container = document.getElementById('container');
// Po selektorze CSS - zwraca pierwszy pasujacy
const paragraph = document.querySelector('.text');
const header = document.querySelector('h1');
// Wszystkie elementy z klasa - zwraca HTMLCollection (live)
const items = document.getElementsByClassName('item');
// Wszystkie elementy po tagu - zwraca HTMLCollection
const divs = document.getElementsByTagName('div');
// Po selektorze CSS - zwraca NodeList (static)
const buttons = document.querySelectorAll('button.primary');
const element = document.querySelector('#info');
// Pobierz tekst (bez tagow HTML)
console.log(element.textContent);
// Zmien tekst
element.textContent = 'Nowy tekst';
// innerHTML - interpretuje tagi HTML (uwaga na XSS!)
element.innerHTML = '<strong>Pogrubiony</strong> tekst';
const link = document.querySelector('a');
// Odczyt atrybutu
console.log(link.getAttribute('href'));
console.log(link.href); // bezposredni dostep
// Ustawienie atrybutu
link.setAttribute('target', '_blank');
link.href = 'https://example.com';
// Usuniecie atrybutu
link.removeAttribute('target');
// Sprawdzenie istnienia
if (link.hasAttribute('disabled')) {
console.log('Link wyłączony');
}
const box = document.querySelector('.box');
// Dodaj klase
box.classList.add('active');
// Usun klase
box.classList.remove('hidden');
// Przełącz (toggle) - dodaj jeśli nie ma, usun jeśli jest
box.classList.toggle('selected');
// Sprawdz czy zawiera
if (box.classList.contains('active')) {
console.log('Box jest aktywny');
}
// Utworz nowy element
const newDiv = document.createElement('div');
newDiv.textContent = 'Nowy element';
newDiv.classList.add('card');
// Dodaj do dokumentu
document.body.appendChild(newDiv);
// Wstaw przed innym elementem
const container = document.querySelector('#container');
const reference = document.querySelector('#reference');
container.insertBefore(newDiv, reference);
const element = document.querySelector('.to-remove');
// Nowoczesna metoda
element.remove();
// Starsza metoda (przez rodzica)
element.parentNode.removeChild(element);
const button = document.querySelector('button');
button.addEventListener('click', function(event) {
console.log('Kliknieto przycisk!');
console.log('Target:', event.target);
});
// Funkcja strzałkowa
button.addEventListener('click', (e) => {
e.preventDefault(); // Zapobiegaj domyslnej akcji
});
ZdarzenieKiedy wystepuje
clickKlikniecie elementu
submitWysłanie formularza
inputZmiana wartości input
keydownNacisniecie klawisza
mouseoverNajechanie myszka
loadZaładowanie strony
// Zamiast dodawać listener do każdego buttona
// Dodajemy jeden do rodzica
document.querySelector('#lista').addEventListener('click', (e) => {
if (e.target.matches('button.delete')) {
e.target.closest('li').remove();
}
});
  • Reflow - ponowne obliczenie layoutu (pozycje, rozmiary)
  • Repaint - ponowne rysowanie elementow (kolory, cienie)
// Źle - wiele reflow
for (let i = 0; i < 100; i++) {
document.body.innerHTML += '<div>Item</div>';
}
// Dobrze - jeden reflow
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const div = document.createElement('div');
div.textContent = 'Item';
fragment.appendChild(div);
}
document.body.appendChild(fragment);
// Zawsze sprawdzaj czy element istnieje
const element = document.getElementById('może-nie-istniec');
if (element) {
element.textContent = 'OK';
}
  • DOM to obiektowa reprezentacja dokumentu HTML
  • Przegladarka tworzy DOM z kodu HTML
  • JavaScript manipuluje DOM przez API przegladarki
  • Selekcja elementow: getElementById, querySelector, querySelectorAll
  • Manipulacja: textContent, innerHTML, classList, setAttribute
  • Zdarzenia obsługujemy przez addEventListener
  • Optymalizuj operacje DOM aby unikac wielu reflow