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

วิธีหาจำนวน Anchor ในเอกสารด้วย JavaScript

หากต้องการดึงจำนวน Anchor (จุดลิงก์ภายในหน้า) ให้ใช้คุณสมบัติ anchors

ตัวอย่าง

ลองรันโค้ดด้านล่างเพื่อดึงจำนวน Anchor ด้วย JavaScript:

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

คำอธิบาย: document.anchors คืนค่า HTMLCollection ของแท็ก <a> ที่มีแอตทริบิวต์ name (named anchors) ไม่รวม <a> ที่มีแค่ href ใช้ .length เพื่อนับจำนวน ใน HTML5 แนะนำใช้ id แทน name สำหรับ fragment identifier