Auto Add target=”_blank” to Links With JavaScript – Target Blank Validate

Category: Javascript | April 21, 2023
AuthorMaiquinho
Last UpdateApril 21, 2023
LicenseMIT
Tags
Views781 views
Auto Add target=”_blank” to Links With JavaScript – Target Blank Validate

Target Blank Validate is a small JavaScript utility that adds target="_blank" to matching anchor links (http or https) on a page.

It helps you apply a consistent new-tab behavior to links after the DOM has loaded, especially on older static pages where you do not want to edit each <a> tag by hand.

How to use it:

1. Download the script or clone the project files, then include index.js at the end of the document.

<script src="yourpath/target-blank-validate/index.js"></script>

2. After the DOM finishes loading, the script scans the page for anchor elements and updates links whose href value contains http.

<a href="https://example.com/docs">Documentation</a>
<!-- After the script runs -->
<a href="https://example.com/docs" target="_blank">Documentation</a>

How it works:

  • Scans <a> elements after DOMContentLoaded.
  • Checks the first attribute value on each anchor for http and https.
  • Sets target="_blank" on matching links.
  • Runs once on the initial page load.

Implementation notes:

The current script checks for http, so it can affect both HTTP and HTTPS links. Review pages that use absolute internal URLs, named link targets, or custom iframe targets before loading them globally.

The script only sets the target attribute. Add rel="noopener" or rel="noreferrer" in your own markup or post-processing step when your project requires explicit rel attributes.

Dynamic links added after the first DOM load will not receive the attribute unless you run similar logic again.

Related Resources:

You Might Be Interested In:


Leave a Reply