Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Created May 6, 2021 15:59
Show Gist options
  • Save mariocesar/f33ff24c4f6642642af06b3c20b7eb51 to your computer and use it in GitHub Desktop.
Save mariocesar/f33ff24c4f6642642af06b3c20b7eb51 to your computer and use it in GitHub Desktop.
Javascript "Vanilla" helpers for different useful cases.

Add a target=_blank and rel=nooopener for all links to outside your page. Useful for security and accesibility

<script>
  Array.prototype.slice.call(document.querySelectorAll("a[href^=http]")).map((el)=> {
    el.setAttribute("target", "_blank");
    el.setAttribute("title", el.href);
    el.setAttribute("rel", "noopener");
  });
</script>

This will convert:

Here is <a href="https://mariocesar.xyz/">my site</a>

To

Here is <a href="https://mariocesar.xyz/" title="https://mariocesar.xyz/" target="_blank" rel="noopener">my site</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment