JS to set a target _Blank on an href with no ID or Class

Hello Guys,

I am working on coding a Javascript that will watch for a click event on an href that does not have an id or class. The links are generated automatically and I can’t add an ID or Class to them. I need the script to watch for the click event and use a target = “_Blank” to open a new window.

Any help would be appreciated.

This is what I have so far but doesn’t work.

Here my code

HTML

<a href=“http://test.com/resources/blog/”>Blog</a>

JS

document.addEventListener(“click”, function (e) {

if (e.event.target.href == “http://test.com/resources/blog/” && !e.target.hasAttribute(“target”)) {
e.target.setAttribute(“target”, “_blank”);
}
});

If you replace

e.target.setAttribute(“target”, “_blank”);

with

alert(‘Hello’);

When you click on the link do you get an alert?

If so why not just use window.open to open the page in a new window/tab.

Also, instead of relying on event propagation you could select all anchors and attach the listener to the link itself. That would probably be better for performance in the long run.

HI Oddz

Thanks for the help

I replaced the code with the following

document.addEventListener(“click”, function (e) {

if (e.event.target.href == “http://test.com/resources/blog/” && !e.target.hasAttribute(“target”)) {
alert(‘Hello’);
}
});

I didn’t get the alert box.

Shouldn’t that be e.target, not e.event.target?

HI Pullo,
you’re right! that worked

Here is my code

document.addEventListener(“click”, function (e) {

if (e.target.href == “http://test.com/resources/blog/” && !e.target.hasAttribute(“target”)) {
alert(‘Hello’);
}
});

I do in fact get an alert box.

Added the target back in there and it works as expected. Thank you and Oddz

Final working code that works

HTML
<a href=“http://test.com/resources/blog/”>Blog</a>

JS
document.addEventListener(“click”, function (e) {
if (e.target.href == “http://test.com/resources/blog/” && !e.target.hasAttribute(“target”)) {
e.target.setAttribute(“target”, “_blank”);
}
});