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

วิธีหา href attribute ของลิงก์ในเอกสารด้วย JavaScript

document.links เป็น collection ของลิงก์ () ในเอกสาร เข้าถึง href ผ่านดัชนีเหมือนอาร์เรย์

ตัวอย่างที่ 1: ลิงก์ที่ 3 (ดัชนี 2)

<html> <body> 
<a href="https://www.tutorialspoint.com/javascript/index.htm">Javascript</a><br> 
<a href="https://www.tutorialspoint.com/java8/index.htm">Java</a><br> 
<a href="https://www.tutorialspoint.com/spring/index.htm">Spring</a> 
<p id="links"></p> 
<script> 
    document.getElementById("links").innerHTML = "The href attribute is: " + document.links[2].href; 
</script> </body> </html>

ผลลัพธ์

The href attribute is: https://www.tutorialspoint.com/spring/index.htm

ตัวอย่างที่ 2: ลิงก์ที่ 1 (ดัชนี 0)

<html> <body> 
<a href="https://www.tutorialspoint.com/javascript/index.htm">Javascript</a><br> 
<a href="https://www.tutorialspoint.com/java8/index.htm">Java</a> 
<p id="links"></p> 
<script> 
    document.getElementById("links").innerHTML = "The href attribute is: " + document.links[0].href; 
</script> </body> </html>

ผลลัพธ์

The href attribute is: https://www.tutorialspoint.com/javascript/index.htm