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

วิธีแสดงจำนวนลิงก์ในเอกสารด้วย JavaScript

หากต้องการดึงจำนวนลิงก์ใน JavaScript ให้ใช้คุณสมบัติ links พร้อม length

ตัวอย่าง

ลองรันโค้ดด้านล่างเพื่อแสดงจำนวนลิงก์ในเอกสาร:

<!DOCTYPE html>
<html>
  <body>
    <a href="https://www.tutorialspoint.com/php">PHP</a>
    <br>
    <a href="https://www.tutorialspoint.com/java/">Java</a>
    <br>
    <a href="https://www.tutorialspoint.com/html5/">HTML</a>
    <br>
    <a href="https://www.tutorialspoint.com/css/">CSS</a>
    <script>
      var val = document.links.length;
      document.write("<br>Number of links in the document: "+val);
    </script>
  </body>
</html>

document.links คืนค่า HTMLCollection ของแท็ก <a> และ <area> ที่มีแอตทริบิวต์ href (hyperlinks) ใช้ .length นับจำนวน ต่างจาก anchors ที่ดูแค่ name attribute