Thuộc tính for trong HTML liên kết phần tử <label> với phần tử có thể gán nhãn (labelable) đầu tiên có id trùng với giá trị của thuộc tính for.
Cú pháp
Cú pháp như sau:
1. Trả về giá trị thuộc tính for:
labelObject.htmlFor
Ví dụ
Ví dụ về thuộc tính for:
<!DOCTYPE html> <html> <head>
<title>Label htmlFor</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
}
input[type="button"] {
border-radius: 10px;
}
</style> </head>
<body>
<form>
<fieldset>
<legend>Label-htmlFor</legend>
<label id="CurrentEditor" for="editorTwo">Biên tập viên hiện tại:</label><br>
<input type="text" id="editorOne" placeholder="editorOne">
<input type="text" id="editorTwo" placeholder="editorTwo">
<input type="button" onclick="getEventData()" value="Đổi biên tập viên">
<div id="divDisplay">Thuộc tính for của label đặt là editor two</div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var labelSelect = document.getElementById("CurrentEditor");
function getEventData() {
if(labelSelect.htmlFor === 'editorTwo'){
divDisplay.textContent = 'Thuộc tính for của label đặt là editor one';
labelSelect.htmlFor = 'editorOne';
}
}
</script> </body> </html>
Đoạn mã trên sẽ tạo ra kết quả như sau:
1) Trước khi nhấn nút 'Đổi biên tập viên':

2) Sau khi nhấn nút 'Đổi biên tập viên':
