GetElementById trong Javascript
Hôm trước ta đã tìm hiểu cách dùng javascript truy cập vào DOM dựa trên số index để truy cập vào từng phần tử, cách đó khá bất tiện khi truy cập ta phải xác định phần tử đó ở index mấy
document.all[0]; // đầu tiên
Hôm nay ta sẽ dùng "getElementById", như tên gọi sẽ lấy phần tử dựa trên id.
Ta có đoạn code html sau:
<div id="show" class="bgStyle">Show here</div>
Ta dùng javascript truy cập vào
var output = document.getElementById('show');
console.log(output); // <div id="show" class="bgStyle">Show here</div>
console.log(output.id); // show
console.log(output.className); // bgStyle
console.log(output.textContent); // Show here
Đoạn javascript trên sẽ truy cập vào phần tử có id là "show" và in ra như id , class , nội dung của thẻ div này.
Bậy giờ chứng ta muốn thay đổi style cho div này, ví dụ chỉnh màu chữ là đỏ, nền vàng, ta làm như sau:
var output = document.getElementById('show');
output.style.color = 'red';
output.style.background = 'yellow';
Hoặc có thể chỉnh sửa padding, hoặc ẩn div này luôn
output.style.padding = '20px';
output.style.display = 'none';
// hoặc hiện lại div này
output.style.display = 'block';
Hoặc muốn thay đổi nội dùng của div
output.innerText = 'Show me';
hoặc có thể thêm nội dung html
output.innerHTML = "<span style='color:blue;'>Show me</span>";
Ta thực hành xem thử nhé:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Tuts</title>
</head>
<body>
<div id="show" class="bgStyle">Show here</div>
<script>
var output = document.getElementById('show');
console.log(output); // <div id="show" class="bgStyle">Show here</div>
console.log(output.id); // show
console.log(output.className); // bgStyle
console.log(output.textContent); // Show here
output.style.color = 'red';
output.style.background = 'yellow';
output.style.padding = '20px';
// ẩn div
// output.style.display = 'none';
// hoặc hiện lại div này
// output.style.display = 'block';
output.innerHTML = "<span style='color:blue;'>Show me</span>";
</script>
</body>
</html>
Vậy là ta đã biết cách dùng document.getElementById()
rồi phải không nào ?