views:

23

answers:

2

I've ended up and done this by hand, but I was thinking this could be done much quicker with some jquery.

I have a table with dozens of the example rows below. What I'd like to do is find the previous siblings of the <a href="#">, grab their URL, change the filetype to .doc and apply.

<tr id="node-20" class="child-of-node-19">
        <td>Tips</td>
        <td>
        <a href="docs/Interview-Info.pdf">
          <img width="20" height="20" src="/images/icons/icon-pdf.gif" alt="PDF" />
        </a> 
        <a href="#">
          <img width="20" height="20" src="/images/icons/icon-word.gif" alt="Microsoft Word" />
        </a>
        </td>
    </tr>

So once the javascript is complete, the generated source would look like this.

<tr id="node-20" class="child-of-node-19">
        <td>Tips</td>
        <td>
        <a href="docs/Interview-Info.pdf">
          <img width="20" height="20" src="/images/icons/icon-pdf.gif" alt="PDF" />
        </a> 
        <a href="docs/Interview-Info.doc">
          <img width="20" height="20" src="/images/icons/icon-word.gif" alt="Microsoft Word" />
        </a>
        </td>
</tr>

My last variation was:

$('a+a[href="#"]').attr('href',$('a+a[href="#"]').prev().attr('href'));

That ends up getting the first url, and applying it to all the <a href="#">. So Interview-Info.pdf is applied to all those links.

This is as far as I got due to time contraints. Is there a simple was to do this?

A: 

you're almost there, try this:

$('a+a[href="#"]').attr('href',$('a+a[href="#"]').prev().attr('href').replace(/.pdf/gi, ".doc"));
Moin Zaman
This won't work for multiple rows
Nick Craver
+1  A: 

.attr() only works with the first element in the set, so you probably want to iterate over your list and apply it to each:

$('a+a[href="#"]').each(function() { 
  $(this).attr('href', $(this).prev().attr('href').replace(/\.[a-z0-9]+$/i, '.doc')); 
});
cbeer
Thanks! This did the trick perfectly. I had tried a variation with "this", but I was using the wrong syntax
Fireflight