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

Thuộc tính text của Option trong HTML DOM

Thuộc tính text của phần tử <option> (trong <select>) trả về hoặc thiết lập **nội dung hiển thị** của tùy chọn. Khác với value (giá trị submit), text là thứ người dùng thấy.

Cú pháp

Lấy giá trị:

optionElement.text

Thiết lập giá trị:

optionElement.text = "Văn bản mới"

Ví dụ: Thay đổi tên hiển thị option

<!DOCTYPE html>
<html>
<head>
    <style>
        html, body { height: 100%; margin: 0; font-family: sans-serif; }
        body {
            text-align: center; color: white;
            background: radial-gradient(circle farthest-corner at 23.1% 64.6%, rgba(129,125,254,1) 0%, rgba(111,167,254,1) 90%) no-repeat;
        }
        .drop-down {
            display: block; width: 35%; margin: 20px auto;
            border: 2px solid white; padding: 8px; font-weight: bold;
            background: rgba(255,255,255,0.1); color: white; outline: none;
        }
        .btn {
            background: orange; border: none; color: white;
            padding: 10px 20px; border-radius: 4px; width: 35%;
            margin: 20px auto; display: block; font-weight: bold; cursor: pointer;
        }
        .show { font-size: 1.5rem; font-weight: bold; margin-top: 20px; }
    </style>
</head>
<body>
    <h1>Demo Option text Property</h1>
    <p>Chọn môn học yêu thích:</p>
    <select class="drop-down" id="subjectSelect">
        <option>Vật lý</option>
        <option>Sinh học</option>
        <option>Toán học</option>
    </select>
    <button onclick="changePhysicsName()" class="btn">Đổi tên "Vật lý" → "Vật lý ứng dụng"</button>
    <div id="result" class="show"></div>
    <script>
        function changePhysicsName() {
            var select = document.getElementById("subjectSelect");
            select.options[0].text = "Vật lý ứng dụng";
            document.getElementById("result").textContent = "Đã đổi: Vật lý → Vật lý ứng dụng";
        }
    </script>
</body>
</html>

Kết quả

Ban đầu:

Thuộc tính text của Option trong HTML DOM

Sau khi nhấn nút đổi tên:

Thuộc tính text của Option trong HTML DOM

🔑 Phân biệt:
  • option.text: Văn bản **hiển thị** cho người dùng.
  • option.value: Giá trị **gửi lên server** khi submit form (mặc định = text nếu không set).
  • Thay đổi text không ảnh hưởng value và ngược lại.