JQuery adds all hyperlink elements that reference PDF files

I would like to add a “Download PDF file” to any hyperlinks associated with the PDF files. Currently I can add this exact text, but it adds it to the text of the hyperlink. I would like it to be outside the hyperlink element, for example: Download a PDF file [text hyperlinks]

This is the code I'm using now:

jQuery('a[href$=.pdf]').prepend('Download a PDF of '); 
+4
source share
4 answers

Have you tried before?

 jQuery('a[href$=.pdf]').before('Download a PDF of '); 
+4
source

The other selectors that were provided in the responses are erroneous to this day. jQuery will complain:

Unused error: syntax error, unrecognized expression: a [href $ =. pdf]

The correct way to select an anchor:

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

Pay attention to quotes around .pdf

+4
source

You can wrap it with an inline element (for example, <span> ) and insert it before the desired elements. Here is SSCCE , just copy ' 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 said earlier, jQuery.before () works exactly the way you want, so I would go after it.

+2
source

Here is an example that will do what you are 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> 
0
source

Source: https://habr.com/ru/post/1299889/


All Articles