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

Thuộc tính type của Anchor trong HTML DOM

Thuộc tính type trong HTML DOM liên quan đến thẻ anchor được dùng để thiết lập hoặc lấy giá trị thuộc tính type của link. Thuộc tính này được giới thiệu trong HTML 5. Thuộc tính này cũng chỉ mang tính chất gợi ý và không bắt buộc. Nó chứa một giá trị MIME type đơn lẻ.

Cú pháp

Trả về thuộc tính type

anchorObject.type

Thiết lập thuộc tính type

anchorObject.type = MIME-type

Ví dụ

Dưới đây là ví dụ cho thuộc tính type của anchor:

<!DOCTYPE html> <html> <body> <p><a id="Anchor" type="text/html" href="https://www.examplesite.com">example site</a></p> <p><a id="Anchor2" href="https://www.example.com">example</a></p> <p>Click các nút để thiết lập và lấy thuộc tính type.</p> <button onclick="getType1()">Lấy Type</button> <button onclick="setType2()">Đặt Type</button> <p id="Type1"></p> <script>    function getType1() {       var x = document.getElementById("Anchor").type;       document.getElementById("Type1").innerHTML = x;    }    function setType2(){       document.getElementById("Type1").innerHTML="Type đã được đặt";       document.getElementById("Anchor2").type="text/html";    } </script> </body> </html>

Kết quả

Ví dụ này sẽ cho kết quả sau:

Thuộc tính type của Anchor trong HTML DOM

Khi click nút Lấy Type:

Thuộc tính type của Anchor trong HTML DOM

Khi click nút Đặt Type:

Thuộc tính type của Anchor trong HTML DOM

Giải thích ví dụ:

Chúng ta lấy hai link với id Anchor và Anchor2 tương ứng. Anchor1 có MIME type text/html, Anchor2 không có MIME type:

<p><a id="Anchor" type="text/html" href="https://www.examplesite.com">example site</a></p> <p><a id="Anchor2" href="https://www.example.com">example</a></p>

Hai nút Lấy Type và Đặt Type để thực thi getType1() và setType2():

<button onclick="getType1()">Lấy Type</button> <button onclick="setType2()">Đặt Type</button>

Hàm getType1() trả về type của anchor với id “Anchor”. Hàm setType2() đặt type của anchor với id “Anchor2” thành text/html.

function getType1() {    var x = document.getElementById("Anchor").type;    document.getElementById("Type1").innerHTML = x; } function setType2(){    document.getElementById("Type1").innerHTML="Type has been set";    document.getElementById("Anchor2").type="text/html"; }