如何在 JavaScript 中查找文档中的链接数量?
在本文中,我们将讨论如何在 JavaScript 中查找文档中的链接数量。
JavaScript 中的 DOM 属性提供了许多属性,例如 <head>、<title>、<body>、<link>、<a>、<style>。我们可以通过两种方式在 HTML DOM 中表示链接。DOM 对象提供 links 属性。
document.links 属性为我们提供了文档内 <a> 和 <area> 标签的集合。document.links 属性类似于数组。我们可以使用此属性访问链接的任何属性(如 href、name、title)。要查找链接的总数,可以使用 length 属性。document.links.length 为我们提供了文档中链接的总数。
语法
下面显示了确定文档中链接数量的语法。
document.links.length
示例 1
以下是一个查找文档中链接数量的示例程序。
<html>
<body>
<a href="https://tutorialspoint.com/javascript/index.htm">Javascript</a><br>
<a href="https://tutorialspoint.com/php/index.htm">Php</a><br>
<a href="https://tutorialspoint.com/java8/index.htm">Php</a><br>
<p id="links"></p>
<script>
document.getElementById("links").innerHTML = "The number of links are: " + document.links.length;
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
示例 2
以下是如何查找文档中链接数量的另一个示例程序。
<!DOCTYPE html>
<html>
<head>
<title>To find the number of links in a document in JavaScript</title>
</head>
<body style="text-align : center">
<h1>To find the number of links in a document in JavaScript</h1>
<a name="google" href="https://www.google.com/" title="Google Home Page">Google</a><br>
<a name="facebook" href="https://#/" title="Facebook Home Page">Facebook</a><br>
<a name="youtube" href="https://www.youtube.com/" title="Youtube Home Page">Youtube</a><br>
<p id="text1"></p>
<script>
document.getElementById("text1").innerHTML = "The total number of links in the document are : "+document.links.length;
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
示例 3
以下示例告诉我们每个链接以及链接总数。
<!DOCTYPE html>
<html>
<head>
<title>To find the number of links in a document in JavaScript</title>
</head>
<body style="text-align : center">
<h1>To find the number of links in a document in JavaScript</h1>
<a name="google" href="https://www.google.com/" title="Google Home Page">Google</a><br>
<a name="youtube" href="https://www.youtube.com/" title="Youtube Home Page">Youtube</a><br>
<p id="text1"></p>
<script>
var result="";
for(var i=0;i<document.links.length;i++){
result += "Link "+(i+1)+" : "+document.links[i].href+"<br/>";
}
document.getElementById("text1").innerHTML = "The links in the document are : "+'<br/>'+result+'<br/>'+"The count for total number of links is : "+document.links.length;
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP