Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách tìm số lượng neo (anchors) trong tài liệu JavaScript


Thẻ neo (Anchor tags) phổ biến khi xử lý tài liệu JS. Có document.anchors.length lấy số lượng neo. Không ảnh hưởng mã khác, chỉ trả độ dài neo.

Cú pháp

length = document.anchors.length;

Chỉ trả số lượng thẻ neo.

Ví dụ 1

Hai thẻ neo, hiển thị độ dài bằng document.anchors.length.

<html> <body> 
    <a name="Tutor">Tutorix</a><br> 
    <a name="Totorial">Tutorialspoint</a><br> 
    <p id="anchors"></p> 
    <script> 
        document.getElementById("anchors").innerHTML = "The number of anchors are: " + document.anchors.length; 
    </script> </body> </html>

Kết quả

Tutorix Tutorialspoint The number of anchors are: 2

Ví dụ 2

Ba thẻ neo, hiển thị độ dài.

<html> <body> 
    <a name="Tutor">Tutorix</a><br> 
    <a name="Totorial">Tutorialspoint</a><br> 
    <a name="Totorials">Tutorialspoint private ltd</a><br> 
    <script> 
        document.write(document.anchors.length); 
    </script> </body> </html>

Kết quả

Tutorix Tutorialspoint Tutorialspoint private ltd 3