DOM (Document Object Model), HTML sayfasının ağaç yapısındaki temsilidir. JavaScript ile bu ağacı gez, oku, değiştir.
Element seçme
// ID ile (tek element)
const el = document.getElementById("title");
// CSS seçicisi ile (ilk eşleşen)
const btn = document.querySelector(".btn");
const first = document.querySelector("ul li:first-child");
// CSS seçicisi ile (hepsi — NodeList)
const items = document.querySelectorAll("li.todo");
items.forEach((li) => console.log(li.textContent));querySelector modern projelerin tek tercihidir. Eski getElementsByClassName/
Tag HTMLCollection döner — canlı bir koleksiyon, kafa karıştırıcı.
İçerik okuma/yazma
const h1 = document.querySelector("h1");
h1.textContent = "Yeni Başlık"; // ✅ güvenli, sadece metin
h1.innerHTML = "<em>Yeni</em>"; // ⚠️ XSS riski (input ile beraber asla)
h1.innerText; // render edilen metin (CSS'i görür)⚠️Güvenlik
Kullanıcıdan gelen veriyi asla innerHTML ile basma.
textContent kullan veya kütüphane ile sanitize et (DOMPurify).
Attribute ve property
const link = document.querySelector("a");
// Attribute
link.getAttribute("href");
link.setAttribute("href", "/blog");
link.removeAttribute("target");
// Property (genelde daha hızlı)
link.href;
link.id = "main-link";
// data-* attribute'leri
// HTML: <div data-user-id="42">
const id = el.dataset.userId; // "42"Class manipülasyonu
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("dark");
el.classList.contains("active"); // true/falseStyle
el.style.color = "red";
el.style.backgroundColor = "yellow"; // camelCase
el.style.cssText = "color: red; padding: 10px"; // toplu
// Daha iyisi: class kullan
el.classList.add("alert");Element oluşturma ve ekleme
const li = document.createElement("li");
li.textContent = "Yeni madde";
li.classList.add("todo");
const ul = document.querySelector("#list");
ul.appendChild(li); // sona ekle
ul.prepend(li); // başa ekle (modern)
ul.insertBefore(li, ul.firstChild);
// Bir seferde HTML yazmak için
ul.insertAdjacentHTML("beforeend", "<li>Madde</li>");Silme ve değiştirme
li.remove(); // kendini sil
ul.removeChild(li); // alternatif
// Tüm çocukları temizle
ul.replaceChildren(); // modern, hepsini sil
ul.innerHTML = ""; // çalışır ama daha yavaşGezme
el.parentElement;
el.children; // sadece element çocuklar
el.firstElementChild;
el.lastElementChild;
el.nextElementSibling;
el.previousElementSibling;
// Yukarı doğru en yakın eşleşen ata
el.closest(".container");Pratik: liste oluştur
const items = ["Elma", "Armut", "Kiraz"];
const ul = document.createElement("ul");
items.forEach((item) => {
const li = document.createElement("li");
li.textContent = item;
ul.appendChild(li);
});
document.body.appendChild(ul);DOM manipülasyonu doğrudan elle React/Vue/Svelte gibi framework'ler çıkmadan önce yaygındı. Bugün de küçük scriptler, prototipler ve framework'lerin altındaki temel olarak şart.