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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: