Change Url of all Anchor Elements using jQuery

Sometime ago I had written about Change the URL of an ASP.NET Hyperlink Control at runtime using jQuery where I had shown how to dynamically change the url of ‘one’ hyperlink control.

However if you have a requirement of changing the url’s of 'multiple' anchor elements at runtime, use this code:

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Change Url's of All Anchor's (from DevCurry.com)</title>
<
script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</
script>

<
script type="text/javascript">
$(function () {
$('a', '#divone').click(function () {
$(this).attr("href", "http://www.devcurry.com");
});
});
</script>
</
head>
<
body>
<
div id="divone">
<
a href="#">One</a>
<
a href="#">Two</a>
<
a href="#">Three</a>
<
a href="#">Four</a>
<
a href="#">Five</a>
</
div>
</
body>
</
html>

The code shown above changes the Href of all the anchor elements inside ‘divone’ to the url www.devcurry.com , and that too with just one line of jQuery code!

Here’s a related article How to convert ASP.NET Bulleted List items or UnOrdered List to Hyperlinks using jQuery

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: