วัตถุ Anchor คืออะไร?
เอลิเมนต์ <a> ใช้สร้างไฮเปอร์ลิงก์ใน HTML พร้อมแอตทริบิวต์ href วัตถุ Anchor (Anchor Object) ใน HTML DOM แทนเอลิเมนต์ <a> นี้ ทำให้ JavaScript สามารถเข้าถึงและจัดการลิงก์ได้
ตัวอย่าง: การเข้าถึงวัตถุ Anchor
<!DOCTYPE html>
<html>
<body>
<h2>ตัวอย่าง Anchor Object</h2>
<a href="https://www.google.com" id="myLink">Google</a><br><br>
<button onclick="showHref()">แสดง URL ของลิงก์</button>
<p id="demo">URL จะแสดงที่นี่</p>
<script>
function showHref() {
var link = document.getElementById("myLink").href;
document.getElementById("demo").innerHTML = link;
}
</script>
</body>
</html>
คุณสมบัติสำคัญของ Anchor Object
| คุณสมบัติ | คำอธิบาย |
|---|---|
href | URL เต็มของลิงก์ (อ่าน/เขียนได้) |
protocol | โปรโตคอล (http:, https:, ftp: ฯลฯ) |
host | โฮสต์ + พอร์ต (เช่น example.com:8080) |
hostname | ชื่อโฮสต์อย่างเดียว (เช่น example.com) |
port | หมายเลขพอร์ต |
pathname | เส้นทางไฟล์ (เช่น /path/page.html) |
search | Query string (ขึ้นต้นด้วย ?) |
hash | Anchor fragment (ขึ้นต้นด้วย #) |
target | ค่าแอตทริบิวต์ target (_blank, _self ฯลฯ) |
rel | ค่าแอตทริบิวต์ rel (noopener, nofollow ฯลฯ) |
ตัวอย่างเพิ่มเติม: แยกส่วนของ URL
<!DOCTYPE html>
<html>
<body>
<a id="myLink" href="https://example.com:8080/path/page.html?query=123#section2">Link</a>
<button onclick="parseURL()">แยกส่วน URL</button>
<div id="output"></div>
<script>
function parseURL() {
var a = document.getElementById("myLink");
var html = "href: " + a.href + "<br>";
html += "protocol: " + a.protocol + "<br>";
html += "host: " + a.host + "<br>";
html += "hostname: " + a.hostname + "<br>";
html += "port: " + a.port + "<br>";
html += "pathname: " + a.pathname + "<br>";
html += "search: " + a.search + "<br>";
html += "hash: " + a.hash;
document.getElementById("output").innerHTML = html;
}
</script>
</body>
</html>
การสร้างลิงก์แบบไดนามิก
สามารถสร้างเอลิเมนต์ <a> ใหม่ด้วย JavaScript ได้:
var link = document.createElement("a");
link.href = "https://example.com";
link.textContent = "ไปที่ Example";
link.target = "_blank";
document.body.appendChild(link);