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>
Tag
Using 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.
<!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 >
</ head >
< body >
< h1 >GeeksforGeeks</ h1 >
</ a >
</ body >
</ html >
|
Output:
Using JavaScript event handling
This 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.
<!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;
}
</ 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 = 'https://www.geeksforgeeks.org/';
});
</ script >
</ body >
</ html >
|
Output: