Thuộc tính label của đối tượng Option trong HTML DOM cho phép lấy hoặc thay đổi giá trị của thuộc tính label của một phần tử <option> trong tài liệu HTML.
Cú pháp
Lấy giá trị label
object.label
Thay đổi giá trị label
object.label = "text"
Ví dụ
Dưới đây là ví dụ minh họa cách sử dụng thuộc tính label của Option:
<!DOCTYPE html>
<html>
<head>
<style>
html { height: 100%; }
body {
text-align: center;
color: #fff;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
height: 100%;
}
p { font-weight: 700; font-size: 1.2rem; }
.drop-down {
width: 35%;
border: 2px solid #fff;
font-weight: bold;
padding: 8px;
}
.btn {
background: #0197F6;
border: none;
height: 2rem;
border-radius: 2px;
width: 35%;
margin: 2rem auto;
display: block;
color: #fff;
outline: none;
cursor: pointer;
}
.show { font-size: 1.5rem; font-weight: bold; }
</style>
</head>
<body>
<h1>Demo thuộc tính label của Option DOM</h1>
<p>Chào bạn, hãy chọn môn học yêu thích:</p>
<select class='drop-down'>
<option label="Vật lý">Vật lý</option>
<option label="Toán học">Toán học</option>
<option label="Hóa học">Hóa học</option>
<option label="Tiếng Anh">Tiếng Anh</option>
</select>
<button onclick="showLabel()" class="btn">Hiển thị giá trị label</button>
<div class="show"></div>
<script>
function showLabel() {
var dropDown = document.querySelector(".drop-down");
var msg = document.querySelector(".show").innerHTML = "Label = " + dropDown.options[dropDown.selectedIndex].label;
console.log(dropDown.options[dropDown.selectedIndex].label);
}
</script>
</body>
</html>
Kết quả
Chọn môn học yêu thích từ danh sách thả xuống và nhấn nút Hiển thị giá trị label để xem giá trị label của tùy chọn đó.