Thuộc tính target trong HTML DOM liên quan đến thẻ anchor (<a>) chỉ định nơi trang web mới sẽ mở sau khi click URL. Có thể có các giá trị sau:
- _blank - Mở tài liệu liên kết trong cửa sổ mới.
- _parent - Mở tài liệu liên kết trong frameset cha.
- _top - Mở tài liệu liên kết trong toàn bộ thân cửa sổ.
- _self - Mở tài liệu liên kết trong cùng cửa sổ. Đây là hành vi mặc định.
- framename - Mở tài liệu liên kết trong framename được chỉ định.
Cú pháp
Trả về thuộc tính target
anchorObject.target
Thiết lập thuộc tính target
anchorObject.target = "_blank|_self|_parent|_top|framename"
Ví dụ
Dưới đây là ví dụ về thuộc tính target của anchor:
<!DOCTYPE html> <html> <body> <p><a id="Anchor" target="_self" href="https://www.examplesite.com">example site</a></p> <p><a id="Anchor2" href="https://www.examplesite.com">example site</a></p> <p>Click nút để xem giá trị thuộc tính target.</p> <button onclick="getTarget1()">Lấy Target</button> <button onclick="setTarget2()">Đặt Target</button> <p id="Target1"></p> <script> function getTarget1() { var x = document.getElementById("Anchor").target; document.getElementById("Target1").innerHTML = x; } function setTarget2(){ document.getElementById("Anchor2").innerHTML="Target đã được đặt"; document.getElementById("Anchor2").target="_blank"; } </script> </body> </html>
Kết quả
Ví dụ này sẽ cho kết quả sau:

Sau khi click nút “Lấy Target”:

Sau khi click nút “Đặt Target”:

Giải thích ví dụ:
Chúng ta lấy một anchor tag với target attribute giá trị _self và một cái với mặc định _blank:
<p><a id="Anchor" target="_self" href="https://www.examplesite.com">example site</a></p> <p><a id="Anchor2" href="https://www.examplesite.com">example site</a></p>
Hai nút Lấy Target và Đặt Target để thực thi getTarget1() và setTarget2():
<button onclick="getTarget1()">Lấy Target</button> <button onclick="setTarget2()">Đặt Target</button>
getTarget1() lấy giá trị target từ link đầu tiên hiển thị trong thẻ p với id=“Target1”. setTarget2() đặt target của link2 từ mặc định _blank thành custom frame “newframe”.
function getTarget1() { var x = document.getElementById("Anchor").target; document.getElementById("Target1").innerHTML = x; } function setTarget2(){ document.getElementById("Target1").innerHTML="Target has been set"; document.getElementById("Anchor2").target="_blank"; }