tags:

views:

679

answers:

4

I am currently trying to use Jquery to change the href attribute of a link within a DIV so that the URL is changed from file.html to file.jpg...

<div class="gallery">
<a href="file.html">My File</a>

and I want to change it to

<div class="gallery">
<a href="file.jpg">My File</a>

I have seen the post about changing the href attribute using Jquery and understand some of it, but I am at a complete loss about how to change all links ending .html within the div to .jpg. The filename doesn't need to change. Would anyone be able to point me in the right direction for help?

+1  A: 

Just extract the existing hrefs for elements whose href matches your pattern, then use string replacement to get the new href and set it.

$('a[href$=.html]').each( function() {
    var $this = $(this);
    var href = $this.attr('href').replace(/\.html/,'.jpg');
    $this.attr('href', href );
});
tvanfosson
+1  A: 
var href=$(".gallery a").attr("href");
href=href.replace(/\.html$/,".jpg");
$(".gallery a").attr("href",href);
mck89
+3  A: 

Try one of these:

$("div.gallery a").each(function() {
    this.setAttribute("href", this.getAttribute("href").replace(/\.html$/, ".jpg"));
});

$("div.gallery a[href$=.html]").each(function() {
    var href = this.getAttribute("href");
    this.setAttribute("href", href.substr(0, href.length-6) + ".jpg"));
});

The first will select every a inside your div and try to replace .html at the end with .jpg using a regular expression. The the second will only select those that’s href value does end with .html and will replace it with .jpg using simple string operations.

Gumbo
A: 

I haven't tested it, but I think this should do it:

$('a', '.gallery').each(function(){
   $(this).attr('href', $(this).attr('href').replace(/\.html$/, '.jpg'));
});
Ryan
thanks everyone! Fantastic help!!!
Jordan