-1

Is there a possibility to open all links in a <form> or a <div> in a new tab? I know there is the target="_blank" but is there a possibility to do this with all links?

j08691
  • 204,283
  • 31
  • 260
  • 272
vished2000
  • 164
  • 1
  • 11

2 Answers2

0

You can write a simple script to do that. Get all anchor tags, iterate and set target as blank programatically.

 <script>
  var elements = document.getElementsByTagName("a");
  for (let item of elements) {
    item.setAttribute("target", "_blank")
  }
 </script>
kokila
  • 294
  • 2
  • 8
  • Yes, but only inside a specifc form or div? – vished2000 May 15 '20 at 14:43
  • var elements = document.querySelectorAll("#myId a"); for (let item of elements) { item.setAttribute("target", "_blank") } where myId is the id of your div or form – kokila May 15 '20 at 17:11
0

Unfortunately, there is no native way of doing this. However, we can apply our own logic with some simple jQuery/js

Note StackOverflow's sandbox doesn't allow popups in snippets due to the allow-popups permission

jQuery:

// For each <a> inside a <form>
$('form a').each(function (i, el) {

  // Set target=_blank
  $(el).attr("target","_blank");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <a href="https://google.com">Google</a>
  <a href="https://twitter.com">Twitter</a>
</form>

JS

// All <forms>
var forms = document.getElementsByTagName('form');
Array.prototype.slice.call(forms).forEach(function (form) {
  
  // All <a>
  var links = form.getElementsByTagName('a');
  Array.prototype.slice.call(links).forEach(function (link) {
  
      // Set target=_blank
      link.setAttribute("target", "_blank")
  })
});
<form>
  <a href="https://google.com">Google</a>
  <a href="https://twitter.com">Twitter</a>
</form>


You can customize the above by changing the hard form or getElementsByTagName('form') to something more specific, like a class selector, or maybe even an id.
Applying target=_blank through CSS would simply this, but it doesn't seem implemented yet.
0stone0
  • 34,288
  • 4
  • 39
  • 64