บทนำ
Property pathname ของ HTMLAreaElement ช่วยให้ดึงเฉพาะส่วนพาธ (path) ของ URL ในแอตทริบิวต์ href ได้ โดยไม่รวม protocol, domain, query string หรือ hash
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<img src="/images/html.gif" alt="HTML Map" border="0" usemap="#html"/>
<map name="html">
<area id="myarea" shape="circle" coords="154,150,59"
href="about.htm" target="_self">
</map>
<script>
var x = document.getElementById("myarea").pathname;
document.write("<br>Pathname: " + x);
</script>
</body>
</html>
ผลลัพธ์
Pathname: /about.htm
คำอธิบาย
- .pathname - คืนค่าพาธของ URL เริ่มต้นด้วย / เสมอ
- หาก href เป็น relative path เช่น
about.htmจะคืนค่า/about.htm - หาก href เป็น absolute URL เช่น
https://example.com/path/page.htmlจะคืนค่า/path/page.html
เปรียบเทียบ URL Properties
สำหรับ URL: https://example.com:8080/path/page.html?query=1#section
| Property | ผลลัพธ์ |
|---|---|
| href | https://example.com:8080/path/page.html?query=1#section |
| protocol | https: |
| host | example.com:8080 |
| hostname | example.com |
| port | 8080 |
| pathname | /path/page.html |
| search | ?query=1 |
| hash | #section |