On my site, I have some links that are built dynamically with JS. Not all of them contain an href value, so I add an href value dynamically. I use javascript:; as that value.
Now, I need to be able to open all links not on my host in a new window. Obviously, javascript:; is not my host, so any link with that in the href attribute will open in a new window.
In the snippet below, I'm trying to prevent that from happening, but I'm not getting the result I desire.
How do I push all offsite links to a new tab, except for one that I specify?
document.querySelectorAll("a:not(a[href])").forEach(element => {
element.setAttribute("href", "javascript:;")
});
var all_links = document.querySelectorAll('a');
for (var i = 0; i < all_links.length; i++) {
var a = all_links[i];
if (a.hostname != location.hostname || a.getAttribute("href") !== 'javascript:;') {
a.rel = 'noopener';
a.target = '_blank';
}
}
<a href="https://yahoo.com">Yahoo!</a>
<hr>
<a>something else</a>
Looks like this was the best solution...
If you inspect each link, you'll see that the external link has _blank, the internal link has _self, and the one with href="javascript:;" has _self.
document.querySelectorAll("a:not(a[href])").forEach(element => {
element.setAttribute("href", "javascript:;")
});
let all_links = document.querySelectorAll('a');
for (var i = 0; i < all_links.length; i++) {
let anchors = all_links[i];
if (anchors.getAttribute('href') == 'javascript:;' || anchors.hostname == location.hostname) {
anchors.target = "_self";
} else {
anchors.target = "_blank";
}
}
<a href="https://yahoo.com">External Link (Yahoo!)</a>
<hr>
<a href="/questions/69563273/change-the-font-and-the-line-spacing-of-a-style">Change the font and the line spacing of a style (SO Question)</a>
<hr>
<a>anchor without href (Goes nowhere)</a>