Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีดึงค่า href attribute ของลิงก์ (Anchor Tag) ใน JavaScript

เพื่อดึงค่า href ของลิงก์ (<a>) ใน JavaScript ให้ใช้ Property .href ซึ่งจะคืนค่า URL แบบเต็มรูปแบบ (Absolute URL) ของเอกสารปลายทาง

ตัวอย่างโค้ด

<!DOCTYPE html>
<html>
  <body>
    <p><a id="anchorid" href="https://www.qries.com/">Qries</a></p>
    <script>
      var myLink = document.getElementById("anchorid").href;
      document.write("Link: " + myLink);
    </script>
  </body>
</html>

คำอธิบาย

  • document.getElementById("anchorid") — เลือก Element ด้วย ID
  • .href — Property ที่คืนค่า URL แบบ Absolute (รวม Protocol, Domain, Path)
  • ผลลัพธ์จะเป็น: Link: https://www.qries.com/

หมายเหตุ: หากต้องการค่า href ตรงตามที่เขียนใน HTML (Relative URL) ให้ใช้ .getAttribute('href') แทน