Nội dung
1. DOM là gì?
DOM hay Document Object Model là một cấu trúc dữ liệu mô tả nội dung, cấu trúc và cách thành phần của tài liệu dưới dạng cây (tree structure)
Mỗi thành phần của tài liệu, chẳng hạn như các thẻ HTML, thuộc tính và nội dung văn bản được biểu diện dưới dạng một node (nút) trong cây DOM
Bằng cách sử dụng Javascript, ta có thực hiện một số tùy chỉnh như lấy, tạo, thêm và xóa các thành phần HTML
2. Getting Element
Để có thể lấy ra và tùy chỉnh các thành phần HTML, ta có rất nhiều cách khách nhau:
Cho ví dụ sau đây:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document Object Model</title>
</head>
<body>
<h1 class="title" id="first-title">First Title</h1>
<h1 class="title" id="second-title">Second Title</h1>
<h1 class="title" id="third-title">Third Title</h1>
<h1></h1>
</body>
</html>
2.1. Getting elements by tag name
Cú pháp:
// syntax
document.getElementsByTagName("tagname");
- Hàm này nhận đối số là tên thẻ và trả về một đối tượng HTMLCollection (HTMLCollection là một mảng các đối tượng thành phần HTML)
- Để có thể truy cập tới từng thành phần này, ta chỉ có thể sử dụng vòng lặp thông thường để lặp qua từng phần tử.
const allTitles = document.getElementsByTagName("h1");
/* Biến allTitles này là một HTMLCollections*/
console.log(allTitles); //HTMLCollections
console.log(allTitles.length); // Độ dài của HTMLCollections là 4
for (let i = 0; i < allTitles.length; i++) {
console.log(allTitles[i]);
}
/* Sử dụng vòng lặp để duyệt qua các thành phần trong HTMLCollections*/
2.2. Getting elements by class name
//syntax
document.getElementsByClassName("classname");
- Hàm này nhận đối số là tên class và trả về một đối tượng HTMLCollection (HTMLCollection là một mảng các đối tượng thành phần HTML)
- Để có thể truy cập tới từng thành phần này, ta chỉ có thể sử dụng vòng lặp thông thường để lặp qua từng phần tử.
const allTitles = document.getElementsByClassName("title");
console.log(allTitles); //HTMLCollections
console.log(allTitles.length); // 4
for (let i = 0; i < allTitles.length; i++) {
console.log(allTitles[i]); // prints each elements in the HTMLCollection
}
2.3. Getting an element by id
//syntax
document.getElementById("id");
Hàm này nhận đối số là tên id không có kí tự # và trả về một đối tượng HTMLCollection (HTMLCollection là một mảng các đối tượng thành phần HTML)
let firstTitle = document.getElementById("first-title");
console.log(firstTitle); // <h1>First Title</h1>
2.4. Getting elements by using querySelector methods
Hàm document.querySelector có thể chọn một thành phần HTML hay nhiều thành phần HTML bằng tên thẻ, id hay tên class tương tự như CSS Selector
querySelector:
- Được sử dụng để chọn thành phần HTML bằng tên thẻ, id hoặc class
- Lưu ý cách chọn này chỉ trả về phần tử HTML đầu tiên.
let firstTitle = document.querySelector("h1"); // select the first available h1 element
let firstTitle = document.querySelector("#first-title"); // select id with first-title
let firstTitle = document.querySelector(".title"); // select the first available element with class title
querySelectorAll
- Được sử dụng để chọn nhiều thành phần HTML có cùng tên thẻ hoặc class
- Hàm này sẽ trả về một nodeList là một mảng các đối tượng thành phần HTML và hỗ trợ các hàm hỗ trợ cho mảng
- Có thể sử dụng vòng lặp để duyệt qua mảng này
const allTitles = document.querySelectorAll('h1') # selects all the available h1 elements in the page
console.log(allTitles.length) // 4
for (let i = 0; i < allTitles.length; i++) {
console.log(allTitles[i])
}
3. Manipulating DOM
3.1. Creating an Element
Để có thể thể tạo thêm một thành phần HTML, ta sử dụng hàm createElement() với đối số truyền vào là tên thẻ
// syntax
document.createElement("tagname");
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<script>
let title = document.createElement("h1");
title.className = "title";
title.style.fontSize = "24px";
title.textContent = "Creating HTML element DOM Day 2";
console.log(title);
</script>
</body>
</html>
3.2. Creating Elements
- Để có thể tạo nhiều thành phần HTML, ta sẽ sử dụng vòng lặp và số lần lặp là số thành phần HTML ta muốn tạo
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<script>
let title;
for (let i = 0; i < 3; i++) {
title = document.createElement("h1");
title.className = "title";
title.style.fontSize = "24px";
title.textContent = i;
console.log(title);
}
</script>
</body>
</html>
3.3. Appending child to a parent element
- Để có thể thêm một thành phần vào một thành phần cha như là một thành phần con, ta cần lấy ra và truy cập tới thành phần HTML cha, sau đó sử dụng hàm
appendChild()
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<script>
// creating multiple elements and appending to parent element
let title;
for (let i = 0; i < 3; i++) {
title = document.createElement("h1");
title.className = "title";
title.style.fontSize = "24px";
title.textContent = i;
document.body.appendChild(title);
}
</script>
</body>
</html>
3.4. Removing a child element from a parent node
Ta có thể xóa một hay nhiều thành phần bằng cách sử dụng removeChild()
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<h1>Removing child Node</h1>
<h2>Asabeneh Yetayeh challenges in 2020</h1>
<ul>
<li>30DaysOfPython Challenge Done</li>
<li>30DaysOfJavaScript Challenge Done</li>
<li>30DaysOfReact Challenge Coming</li>
<li>30DaysOfFullStack Challenge Coming</li>
<li>30DaysOfDataAnalysis Challenge Coming</li>
<li>30DaysOfReactNative Challenge Coming</li>
<li>30DaysOfMachineLearning Challenge Coming</li>
</ul>
<script>
/* Sử dụng querySelector để lấy ra thẻ ul */
const ul = document.querySelector('ul')
/* Sử dụng querySelectorAll để lấy ra tất cả thẻ li*/
const lists = document.querySelectorAll('li')
/* Sử dụng vòng lặp duyệt qua mảng các thẻ li và gọi hàm removeChild() thực hiện xóa từng thẻ li khỏi thẻ ul */
for (const list of lists) {
ul.removeChild(list)
}
</script>
</body>
</html>
Bên cạnh đó, ta cũng có thể sử dụng .innetHTML để thực hiện xóa thành phần HTML như sau:
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<h1>Removing child Node</h1>
<h2>Asabeneh Yetayeh challenges in 2020</h1>
<ul>
<li>30DaysOfPython Challenge Done</li>
<li>30DaysOfJavaScript Challenge Done</li>
<li>30DaysOfReact Challenge Coming</li>
<li>30DaysOfFullStack Challenge Coming</li>
<li>30DaysOfDataAnalysis Challenge Coming</li>
<li>30DaysOfReactNative Challenge Coming</li>
<li>30DaysOfMachineLearning Challenge Coming</li>
</ul>
<script>
const ul = document.querySelector('ul')
ul.innerHTML = ''
</script>
</body>
</html>
4. Event Listeners
4.1. Event
- Bên cạnh các sự kiện như:
onclick,onchange,onmouseover,onmouseout,onkeydown,onkeyup,onload, ta có thể thêm lắng nghe sự kiện bằng cách sử dụng hàmaddEventListener()để lắng nghe các sự kiện khác nhau của các thành phần HTML
selectedElement.addEventListener("eventlistner", function (e) {
// the activity you want to occur after the event will be in here
});
- Hàm
addEventListener()này nhận hai đối số làtên sự kiện,hàm callback
- Sự kiện Click chuột
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model</title>
</head>
<body>
<button>Click Me</button>
<script>
const button = document.querySelector("button");
button.addEventListener("click", (e) => {
console.log("e gives the event listener object:", e);
console.log("e.target gives the selected element: ", e.target);
console.log(
"e.target.textContent gives content of selected element: ",
e.target.textContent
);
});
</script>
</body>
</html>
Ta cũng có thể lắng nghe sự kiện trực tiếp trong thành phần HTML như sau:
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model</title>
</head>
<body>
<button onclick="clickMe()">Click Me</button>
<script>
const clickMe = () => {
alert("We can attach event on HTML element");
};
</script>
</body>
</html>
- Sự kiện mouse enter
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model</title>
</head>
<body>
<button>Click Me</button>
<script>
const button = document.querySelector("button");
button.addEventListener("mouseenter", (e) => {
console.log("e gives the event listener object:", e);
console.log("e.target gives the selected element: ", e.target);
console.log(
"e.target.textContent gives content of selected element: ",
e.target.textContent
);
});
</script>
</body>
</html>
Ngoài ra, ta còn có các sự kiện như sau
- click - Khi phần tử được nhấp chuột.
- dblclick - Khi phần tử được nhấp chuột hai lần liên tiếp.
- mouseenter - Khi con trỏ chuột di chuyển vào trong phần tử.
- mouseleave - Khi con trỏ chuột rời khỏi phần tử.
- mousemove - Khi con trỏ chuột di chuyển trên phần tử.
- mouseover - Khi con trỏ chuột di chuyển vào phần tử hoặc phần tử con bên trong.
- mouseout - Khi con trỏ chuột rời khỏi phần tử hoặc rời khỏi phần tử con bên trong.
- input - Khi giá trị được nhập vào trường nhập liệu (
input). - change - Khi giá trị của trường nhập liệu (
input) thay đổi và người dùng rời khỏi trường đó. - blur - Khi phần tử không còn được chọn (mất tiêu điểm).
- keydown - Khi một phím được nhấn xuống.
- keyup - Khi một phím được nhả ra.
- keypress - Khi một phím được nhấn (hiện nay thường thay bằng
keydownvì sự kiện này đã không còn được khuyến nghị sử dụng). - onload - Khi trình duyệt đã tải xong một trang.
4.2. Getting value from an input element
Ta sử dụng form để thu nhập thông tin nhập từ người dùng, để làm được điều đó hãy xem ví dụ sau đây
- input value
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<h1>Body Mass Index Calculator</h1>
<input type="text" id="mass" placeholder="Mass in Kilogram" />
<input type="text" id="height" placeholder="Height in meters" />
<button>Calculate BMI</button>
<script>
const mass = document.querySelector("#mass");
const height = document.querySelector("#height");
const button = document.querySelector("button");
let bmi;
button.addEventListener("click", () => {
bmi = mass.value / height.value ** 2;
alert(`your bmi is ${bmi.toFixed(2)}`);
console.log(bmi);
});
</script>
</body>
</html>
- input / change / blur event
Bên cạnh việc lấy ra giá trị của ô nhập, ta có thể lắng nghe được sự kiện nhập của hay thay đổi của ô input. Hay là sự kiện blur khi ô input không còn được focus nữa
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<h1>Data Binding using input or change event</h1>
<input type="text" placeholder="say something" />
<p></p>
<script>
const input = document.querySelector("input");
const p = document.querySelector("p");
input.addEventListener("input", (e) => {
p.textContent = e.target.value;
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<h1>Giving feedback using blur event</h1>
<input type="text" id="mass" placeholder="say something" />
<p></p>
<script>
const input = document.querySelector("input");
const p = document.querySelector("p");
input.addEventListener("blur", (e) => {
p.textContent = "Field is required";
p.style.color = "red";
});
</script>
</body>
</html>
- keypress, keydown and keyup
Lắng nghe sự kiện gõ phím như thế nào?
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<h1>Key events: Press any key</h1>
<script>
document.body.addEventListener("keypress", (e) => {
alert(e.keyCode);
});
</script>
</body>
</html>
