Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Đối tượng Label trong HTML DOM

Đối tượng Label trong HTML DOM đại diện cho phần tử <label>.

Cú pháp

Tạo một phần tử <label>:

var labelObject = document.createElement("LABEL")

Các thuộc tính

Đối tượng LabelObject có thể có các thuộc tính sau:

Thuộc tínhMô tả
controlTrả về điều khiển của label
formTrả về tham chiếu của form bao quanh chứa label
htmlForTrả về/thiết lập giá trị của thuộc tính for của một label

Ví dụ

Ví dụ minh họa thuộc tính Label htmlFor:

<!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="Thay đổi biên tập viên"> <div id="divDisplay">Thuộc tính for của label được đặ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 = 'Label for attribute set as editor one'; labelSelect.htmlFor = 'editorOne'; } } </script> </body> </html>

Kết quả

Trước khi nhấn nút 'Thay đổi biên tập viên':

Đối tượng Label trong HTML DOM

Sau khi nhấn nút 'Thay đổi biên tập viên':

Đối tượng Label trong HTML DOM