views:

327

answers:

3

I would like to prepend "Download a PDF of " to any hyperlinks, linking to PDF files. Currently I'm able to prepend that exact text, but it prepends it to the hyperlink text. I would like it to reside outside of the hyperlink element, like so: Download a PDF of [hyperlink with text]

This is the code I'm using now:

jQuery('a[href$=.pdf]').prepend('Download a PDF of ');
+4  A: 

Have you tried before?

jQuery('a[href$=.pdf]').before('Download a PDF of ');
AlteredConcept
+1 great answer. It works: http://jsbin.com/akiba3 I confess, I took @BalusC's SSCCE and changed the one line out to use your solution to run my test.
Doug Neiner
Sweet! I <3 jQuery. It makes my life so much easier. =D
AlteredConcept
+1 indeed. Didn't realize of this one.
BalusC
Simple and easy, thanks again for the help!
Hunter Satterwhite
+1 I too had typed up Balus' answer, but discarded it when seeing this one :) Nice work, @AlteredConcept.
Jonathan Sampson
+1  A: 

You could wrap it up in an inline element (e.g. <span>) and insert it before the desired elements. Here's an SSCCE, just copy'n'paste'n'run it:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2172666</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt;
        <script>
            $(document).ready(function() {
                $('<span>Download a PDF of </span>').insertBefore('a[href$=.pdf]');
            });
        </script>
    </head>
    <body>
        <p><a href="foo.pdf">foo.pdf</a></p>
        <p><a href="foo.exe">foo.exe</a></p>
        <p><a href="bar.pdf">bar.pdf</a></p>
    </body>
</html>

Edit: ah, as answered before, the jQuery.before() works exactly the way you want, so I would go for it instead.

BalusC
The `span` isn't needed, but it is needed using it the way you show here (with `$()` and `insertBefore`) but +1 for updating your answer and providing a working example.
Doug Neiner
Yes exactly. I just wasn't fully aware about the existence and benefit of `before()`. Now I do :)
BalusC
A: 

Here's an example that will do what you're looking for:

<a href="foo.pdf">Foo</a>
<a href="bar.pdf">Bar</a>
<span id='foo'>Download a pdf of </span>
<script type='text/javascript'>
$('#foo').insertBefore('a[href$=.pdf]');
</script>
monksp