Skip to content

Instantly share code, notes, and snippets.

@serdarwork
Created March 17, 2021 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serdarwork/e1a37dd1015f22e5add5813b477f8478 to your computer and use it in GitHub Desktop.
Save serdarwork/e1a37dd1015f22e5add5813b477f8478 to your computer and use it in GitHub Desktop.
JAVASCRIPT: Add target="_blank" to links within specificied div(s)
// Specify div(s)
const fieldNames = ['.more-link', '#featured-posts a', '.page-link a'];
// Select div(s)
const selectFields = fieldNames.map((field) => document.querySelectorAll(field));
selectFields.forEach((e, i) => {
if (selectFields[i].length > 0) {
// Get links within a specificied div
const linkArray = Array.prototype.slice.call(e);
// Add target="_blank" attribute to links
linkArray.forEach((link) => link.setAttribute('target', '_blank'));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment