如何在JavaScript中查詢文件中錨點的數量?
本文討論瞭如何在JavaScript中查詢文件中錨點的數量。錨點標籤是HTML DOM元素的一部分。anchor屬性是一個只讀屬性,它返回文件內錨點標籤的列表。錨點物件表示為<a>。
有兩種方法可以獲取錨點物件的長度。一種方法是使用anchors.length屬性,它返回文件中錨點標籤的數量。另一種方法是使用getElementByTagName方法訪問錨點標籤並使用length屬性。兩者內部都會計算文件中<a>標籤的數量。
語法
下面顯示了查詢文件中錨點數量的語法。
document.anchors.length or document.getElementsByTagName("a").length
讓我們看看這些例子:
示例1
在下面的例子中,使用了三個錨點標籤,並使用document.anchors.length顯示了它們的長度,如輸出所示。
<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>
執行上述程式碼後,將生成以下輸出。
示例2
以下是一個查詢文件中錨點數量的示例程式。
<html>
<head>
<title>How to find the number of anchors in a document in JavaScript</title>
</head>
<h3>To find the number of anchor tags in a document</h3>
<body style = "text-align:center;">
<p>The most popular websites that are used by young generation are :</p>
<a href="#">Google</a> <br/>
<a href="#">Facebook</a> <br/>
<a href="#">Instagram</a> <br/>
<p id="text1"></p>
<script type="text/javascript">
document.getElementById("text1").innerHTML = "The number of anchor tags is : "+document.getElementsByTagName("a").length;
</script>
</body>
</html>
執行上述程式碼後,將生成以下輸出。
示例3
以下是一個計算特定div標籤內錨點標籤數量的示例程式。
<!DOCTYPE HTML>
<html>
<head>
<title>How to find the number of anchors in a document in JavaScript</title>
<head>
<h3>To find the number of anchor tags in a document</h3>
<body style = "text-align:center;">
<p>The most popular websites that are used by young generation are :</p>
<div id="websites">
<a href="#">Google</a> <br/>
<a href="#">Facebook</a> <br/>
<a href="#">Instagram</a> <br/>
</div>
<p>The most popular cars are :</p>
<div id="Cars">
<a href="#">BMW</a> <br/>
<a href="#">AUDI</a> <br/>
<a href="#">RANGE ROVER</a> <br/>
<a href="#">MARUTI SUZUKI</a> <br/>
</div>
<p id="text1"></p>
<script type="text/javascript">
var count = document.getElementById("Cars").getElementsByTagName("a").length;
document.getElementById("text1").innerHTML = "The number of anchor tags for the mentioned div tag 'Cars' is : "+count;
</script>
</body>
</html>
執行上述程式碼後,將生成以下輸出。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP