jQuery each() change href attribute for all hyperlinks

Introduction

Use the jQuery .attr() method to dynamically set the value of href attribute of a link.

Convert all hyperlinks or links in an HTML document from "http" to "https".

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Change HREF Attribute of Anchor Tag Dynamically</title>
<script src="https://code.jquery.com/jquery-1.12.4.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
        });/*w  w  w.j a  v a 2 s. c o m*/
    });
</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>



PreviousNext

Related