You can use the jQuery .attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.
The following example will show you how to convert all hyperlinks or links in an HTML document from "http" to "https" when the document becomes ready with jQuery.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set HREF for Anchor Tag</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$('a[href^="http://"]').each(function(){
var oldUrl = $(this).attr("href"); // Get current url
var newUrl = oldUrl.replace("http://", "https://"); // Create new url
$(this).attr("href", newUrl); // Set herf value
});
});
</script>
</head>
<body>
<p><a href="http://www.google.com">Google</a></p>
<p><a href="http://www.gmail.com">Gmail</a></p>
</body>
</html>
Use the jQuery
.attr()MethodYou can use the jQuery
.attr()method to dynamically set or change the value ofhrefattribute of a link or anchor tag. This method can also be used to get the value of any attribute.The following example will show you how to convert all hyperlinks or links in an HTML document from "http" to "https" when the document becomes ready with jQuery.
need an explanation for this answer? contact us directly to get an explanation for this answer