Tiếp tục Bài 11 – DOM trong JavaScript. Đây là nền tảng giúp bạn tương tác trực tiếp với HTML, thay đổi nội dung, thêm/xóa phần tử, và tạo hiệu ứng trên trang web bằng JavaScript.
1. DOM là gì?
DOM (Document Object Model) là mô hình dạng cây mô tả toàn bộ nội dung HTML của một trang web.
→ JavaScript dùng DOM để truy cập và điều khiển các phần tử HTML.
2. Truy cập phần tử trong HTML
getElementById
<p id="demo">Xin chào</p>
<script>
let el = document.getElementById("demo")
console.log(el.innerText)
</script>
getElementsByClassName / getElementsByTagName
<p class="note">A</p>
<p class="note">B</p>
<script>
let list = document.getElementsByClassName("note")
console.log(list[0].innerText) // A
</script>
querySelector và querySelectorAll
<p class="text">Hello</p>
<script>
let el = document.querySelector(".text") // chọn 1
let els = document.querySelectorAll(".text") // chọn nhiều
</script>
3. Thay đổi nội dung HTML
innerText
document.getElementById("demo").innerText = "Chào bạn!"
innerHTML
document.getElementById("demo").innerHTML = "<b>Xin chào</b>"
4. Thay đổi thuộc tính
document.getElementById("myImg").src = "anh-khac.jpg"
document.getElementById("myLink").href = "https://google.com"
5. Thêm và xoá phần tử
let newP = document.createElement("p")
newP.innerText = "Đây là đoạn mới"
document.body.appendChild(newP)
let old = document.getElementById("demo")
old.remove()
6. Thay đổi class/style
let el = document.getElementById("box")
el.classList.add("highlight")
el.style.color = "red"
el.style.fontSize = "20px"
7. Giao diện học (code + output)
| HTML | JS | Kết quả |
|---|---|---|
<p id="demo">Hi</p> | innerText = "Hello" | Đổi thành “Hello” |
<img id="myImg" /> | src = "a.jpg" | Đổi ảnh |
<div id="box"></div> | style.backgroundColor = "blue" | Đổi màu nền |
Tóm tắt bài 11
Bạn đã học:
- DOM là cầu nối giữa HTML và JavaScript
- Truy cập phần tử bằng
getElementById,querySelector,… - Thay đổi nội dung với
innerText,innerHTML - Sửa style, class, thuộc tính, thêm/xoá phần tử
Bài tập
- Tạo 1 thẻ
<p>cóid="greeting"và đổi nội dung bằng JS - Thêm một nút “Xoá” → khi bấm sẽ xoá dòng chữ
- Thêm 1 đoạn văn mới vào cuối trang

Thảo luận