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

No comments:

Post a Comment