Javascript: Google Analytics Track Outbound Page Views
I would write this code like:

Array.prototype
  .slice
  .call(document.getElementsByTagName("a")) // Get all links from the page
  .forEach(function (link) { // Loop through them
    const isExternal = link.hostname != document.location.hostname;  // Check if is external
    const isPDF = link.href.indexOf(".pdf") &gt; -1; // Check is is PDF
    if(isExternal || isPDF){
      link.setAttribute("onClick", "javascript: trackOutboundLink('" + link.href + "');"); // set onClick attribute
    }
  })


Update #1

Using ES6, you can do something like this:

// Get all the links from the page
const links = [...document.getElementsByTagName('a')];

// "Explain what a pdf link is"
const isPDF = link =&gt; link.href.endsWith('.pdf');

// "Explain what an external is"
const isExternal = link =&gt; link.hostname != document.location.hostname;

// "Explain what links you want to target"
const target = link =&gt; isPDF(link) || isExternal(link);

// "Explain what should be done to those links"
const onClick = link =&gt; link.setAttribute('onClick', `javascript: trackOutboundLink('${link.href}');`);

// Filter and do the work
links.filter(target).map(onClick);


I would suggest the second method, because it's much more clear, pure and very easy to test.