HTML DOM Elements

در جاوااسکریپت، هر عنصر HTML یک DOM Element است که می‌توان به آن دسترسی داشت و ویژگی‌ها، محتوا، استایل و رویدادهای آن را تغییر داد.
DOM Elements نقطه اصلی تعامل با ساختار صفحه وب هستند.

🔹 1. دسترسی به عناصر

با document.getElementById

let title = document.getElementById("myTitle"); console.log(title.innerText);

با document.getElementsByClassName

let items = document.getElementsByClassName("item"); console.log(items[0].innerText);

با document.getElementsByTagName

let divs = document.getElementsByTagName("div");

با document.querySelector و document.querySelectorAll

let firstItem = document.querySelector(".item"); let allItems = document.querySelectorAll(".item");

🔹 2. تغییر محتوا

  • متن عنصر: innerText یا textContent

title.innerText = "New Title";
  • HTML داخلی: innerHTML

let container = document.getElementById("container"); container.innerHTML = "<p>New Paragraph</p>";
  • HTML خارجی (شامل خود عنصر): outerHTML

title.outerHTML = "<h2>Replaced Title</h2>";

🔹 3. مدیریت Attributes

  • getAttribute(attr) → دریافت مقدار Attribute

  • setAttribute(attr, value) → تغییر یا اضافه کردن Attribute

  • removeAttribute(attr) → حذف Attribute

let link = document.querySelector("a"); link.setAttribute("href", "https://example.com"); console.log(link.getAttribute("href")); link.removeAttribute("target");

🔹 4. مدیریت کلاس‌ها

  • اضافه کردن کلاس: classList.add("className")

  • حذف کلاس: classList.remove("className")

  • بررسی کلاس: classList.contains("className")

  • تغییر کلاس: classList.toggle("className")

let box = document.getElementById("box"); box.classList.add("active"); box.classList.toggle("highlight"); console.log(box.classList.contains("active")); // true

🔹 5. تغییر استایل عناصر

let box = document.getElementById("box"); box.style.backgroundColor = "red"; box.style.width = "200px"; box.style.border = "2px solid black";

🔹 6. مدیریت رویدادها

  • addEventListener(event, handler) → اضافه کردن رویداد

  • removeEventListener(event, handler) → حذف رویداد

let btn = document.getElementById("myBtn"); btn.addEventListener("click", () => { alert("Button clicked!"); });

🔹 7. ایجاد و حذف عناصر

  • ایجاد عنصر: document.createElement(tagName)

  • اضافه کردن به DOM: appendChild, insertBefore

  • حذف عنصر: remove()

  • جایگزینی عنصر: replaceChild(newElement, oldElement)

let newDiv = document.createElement("div"); newDiv.innerText = "Hello Element"; document.body.appendChild(newDiv);

✅ خلاصه

  • DOM Element → هر عنصر HTML که می‌توان با آن تعامل داشت

  • دسترسی به عناصر: getElementById, getElementsByClassName, querySelector

  • مدیریت محتوا: innerText, textContent, innerHTML, outerHTML

  • مدیریت Attributes و کلاس‌ها

  • تغییر استایل، رویدادها و ایجاد/حذف عناصر