1

I'm using a CMS where I cannot change the html. But they do give the ability to add javascript to the page.

There's a link in the usual format e.g. <a id="myid" href="">Link</a>

What's the best way to open this in a new window?

(It is on a page with a form. So it's one occasion where forcing a new window is definitely required to keep the text filled in on the form from being cleared by a change of page)

  • Add target attribute with value _blank like this, ```target="_blank"```. visit https://www.w3schools.com/tags/att_a_target.asp for more info – Nexo Oct 21 '22 at 16:42
  • Thanks. I don't have the ability to change the html. So I can't add target="_blank" to the a element. – user3369743 Oct 21 '22 at 17:20
  • Yes, it's surprising that some missed that limitation since it's clearly stated in the question. – Yogi Oct 21 '22 at 17:34

1 Answers1

2

If you can't set target attribute on the <a> tag but you can set an id, then this code should work:

document.getElementById('idOfLinkYouWantToOpenInADifferentWindow').target = '_blank';

If you can't add an ID, then you can target href directly, like this:

document.querySelector('a[href=https://www.google.fr/]').target = '_blank';
Valentin
  • 10,769
  • 2
  • 17
  • 27
  • 1
    Up vote because this answers the question of how content editors, with limited rights, can customize generated html. It's a common problem in enterprise CMS environments. – Yogi Oct 21 '22 at 17:20
  • Thanks! I added another solution targeting href directly by editing my answer. – Valentin Oct 21 '22 at 20:06