4

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 Answers4

6

Have you tried before?

jQuery('a[href$=.pdf]').before('Download a PDF of ');
AlteredConcept
  • 2,602
  • 7
  • 32
  • 36
5

The other selectors that have been provided in answers are wrong, as of today anyway. jQuery will complain:

Uncaught Error: Syntax error, unrecognized expression: a[href$=.pdf]

The right way to select the anchor is:

jQuery('a[href$=".pdf"]');

Note the quotes around .pdf

2

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"></script>
        <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
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 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 Jan 31 '10 at 18:05
  • Yes exactly. I just wasn't fully aware about the existence and benefit of `before()`. Now I do :) – BalusC Jan 31 '10 at 18:13
0

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
  • 929
  • 6
  • 14