Giới thiệu
Thuộc tính id của DOM Element đọc hoặc gán định danh duy nhất (unique identifier) cho phần tử. Giá trị phải duy nhất trong tài liệu. Dùng cho CSS selector (#id), JavaScript (getElementById), anchor link, v.v.
Cú pháp
// Lấy element.id // Gán element.id = "gia_tri_moi"
Ví dụ minh họa
<!DOCTYPE html>
<html>
<head>
<style>
p { background:#347924; color:#fff; padding:8px; }
.show { margin:8px; color:#347924; font-size:18px; font-weight:bold; }
</style>
</head>
<body>
<h1>Ví dụ id Property</h1>
<p id="Awesome-para">Đoạn văn có id "Awesome-para"</p>
<button onclick="getId()">Hiện Id</button>
<button onclick="changeId()">Đổi Id</button>
<div class="show"></div>
<script>
function getId() { document.querySelector(".show").innerHTML = document.querySelector('p').id; }
function changeId() { document.querySelector('p').id = "ID-Changed"; document.querySelector(".show").innerHTML = 'id mới là "ID-Changed"'; }
</script>
</body>
</html>
Kết quả hiển thị
Nhấn "Hiện Id" -> hiện "Awesome-para". Nhấn "Đổi Id" -> id thay thành "ID-Changed" (xem Inspect Element).