Home » Javascript

JavaScript - Print All Links (Hyperlinks) with HREF Attribute, Total Number of Links in a Page

In this code snippet, we will learn how to get total number of links (hyperlinks) of a webpage using JavaScript and How to print HREF and innerHTML attributes using JavaScript function.

JavaScript Code Snippet - Get All Links of a Webpage using JavaScript Function

CSS

<script type="text/javascript">
	function getTotalLinks(){
		var n=document.links.length;
		document.getElementById("pLinks").innerHTML="Total number of links: " + n;				
	}
	
	function printAllLinks(){
		var totalLinks=document.links.length;
		document.getElementById("pLinks").innerHTML="";
		for(var i=0;i<totalLinks;i++){
			document.getElementById("pLinks").innerHTML+=
				"Link: " + document.links[i].innerHTML +
				" is linked to: " + document.links[i].href+"<br/>";
		}
	}
</script>

HTML Source Code with CSS

<!--JavaScript - Print All Links (Hyperlinks) with HREF Attribute, Total Number of Links in a Page.-->
<html>
	<head>
		<title>JavaScript - Print All Links (Hyperlinks) with HREF Attribute, Total Number of Links in a Page.</title>
		<!--Example CSS-->
		<link href="ExampleStyle.css" type="text/css" rel="stylesheet"/>
		
		<script type="text/javascript">
			function getTotalLinks(){
				var n=document.links.length;
				document.getElementById("pLinks").innerHTML="Total number of links: " + n;				
			}
			
			function printAllLinks(){
				var totalLinks=document.links.length;
				document.getElementById("pLinks").innerHTML="";
				for(var i=0;i<totalLinks;i++){
					document.getElementById("pLinks").innerHTML+=
						"Link: " + document.links[i].innerHTML +
						" is linked to: " + document.links[i].href+"<br/>";
				}
			}
		</script>
	</head>
	<body>
		<h1>JavaScript - Print All Links (Hyperlinks) with HREF Attribute, Total Number of Links in a Page.</h1>
		<p>
			<a href="www.wikihow.com">WikiHow</a>
			<a href="www.wikipedia.org">wikiPedia</a>
		</p>		
		<input type="button" value="Get total links." onclick='getTotalLinks()'/>
		<input type="button" value="Print All Links." onclick='printAllLinks()'/>
		<p id="pLinks"></p>
	</body>
</html>

Result

get all links from webpage using javascript function




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.