Maria-Andersado
Maria-Andersado

Reputation: 817

Generating a Direct Link to Embed PDFs

I'm trying to create a JQuery function that will automatically find embed PDF URLs on my website and generate a link that goes directly to the PDF right before it's embed. All embed PDF links will be found in an html tag called object. So every instance of a PDF will look like this:

<object data="http://website.com/directLink.pdf" type="pdf"> 
<a heref="http://website.com/directLink.pdf">...</a></object>

Is there a simple way to extract the URL and generate a link with it right after the object tag? I'd want the resulting link to look something like this:

Download this document <a href="http://website.com/directLink.pdf">here</a>

I don't want to change the existing DOM, just generate the above code after it.

Upvotes: 0

Views: 122

Answers (1)

sg.cc
sg.cc

Reputation: 1826

I would do something like this (untested, quick solution):

// Grab all objects on the page
var objects = document.querySelectorAll('object');

// Iterate through objects
for( var i = 0; i < objects.length; i++ ) {
  var el = objects[i];
  var href = el.getAttribute('data');
  // Check if the URL contains a PDF link; append link if it does
  if( ~href.indexOf('.pdf') {
    var link = document.createElement('a');
    link.href = href;
    el.parentNode.appendChild(link);
  }
}

Upvotes: 1

Related Questions