How to Force Markdown Links to Open in a New Tab (without jQuery)

by Bradley Gauthier

While creating links in Markdown is relatively painless. Adding additional attributes to the links to ensure the click opens in a new tab isn't as simple.

I usually prefer all external links to open in a new browser tab. Which has an important benefit: your website still remains in the browser once the visitor is finished with the linked page.

A website visitor is important to you so you don't want to lose them to one of your links.

And best yet? This solution doesn't require jQuery!

How to Add Attributes to a Markdown Link

With the below Javascript, you can easily add classes and more to your links. This is incredibly straightforward. Simply add this to your existing JavaScript:

(function() {
  var links = document.links;
  for (var i = 0, linksLength = links.length; i < linksLength; i++) {
    if (links[i].hostname != window.location.hostname) {
      links[i].target = "_blank";
      links[i].setAttribute("rel", "noopener noreferrer");
      links[i].className += " externalLink";
    } else {
      links[i].className += " localLink";    

For security measures, please remember to ALWAYS add rel="noopener" to external links. Without the attribute, you are opening your site up to malicious uses. And noreferrer is a little trick to keep your privacy, as it should hide you from their analytics.

I've used this little code snippet all over the place for years, so I hope you find it valuable!

Bradley Gauthier

Brad is the founder of Sitecast. He's a life-long coder and entrepreneur. When not coding, he can be found outside exploring nature. Learn more about him on his personal site.