To transform a <div> into a link, use the we can use anchor tag by wrapping the <div> with it. Set the href attribute of the anchor tag to the desired URL or target location. In this example we will see multiple approaches to do so:
Using the <a> TagUsing the <a> tag, you can turn an HTML element into a link by wrapping it with an anchor tag and setting the href attribute to the desired URL.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Div as Link</title>
<style>
/* Ensure the link behaves like a block element */
.link-container {
display: block;
text-decoration: none; /* Remove default underline */
color: inherit; /* Inherit text color */
}
/* Style the heading within the link */
.link-container h1 {
margin: 0; /* Remove default margin */
padding: 20px; /* Add padding for better click area */
background-color: #f0f0f0; /* Optional: add background color */
text-align: center; /* Center align the text */
}
</style>
</head>
<body>
<a href="/archive/" class="link-container">
<h1>GeeksforGeeks</h1>
</a>
</body>
</html>
Output:
 Using JavaScript event handlingThis approach involves attaching a click event listener to the <div> element, that redirects to a specified URL on clicking the <div>.
Example: Implementation to change div to link by using javascript event handling.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Event Handling</title>
<style>
#divLink {
padding: 10px;
background-color: lightblue;
cursor: pointer;
text-align: center; /* Center text inside the div */
border: 1px solid #ccc; /* Optional: add a border for better visibility */
border-radius: 5px; /* Optional: add rounded corners */
}
</style>
</head>
<body>
<div id="divLink">
Click in this div to go to GeeksforGeeks
</div>
<script>
document.getElementById('divLink').addEventListener('click', function () {
window.location.href = '/archive/';
});
</script>
</body>
</html>
Output:

|