Open external links in a new tab without jQuery

前端 未结 3 594
挽巷
挽巷 2020-12-30 10:27

What\'s the best way to open all external links (URLs that don\'t match the current domain) in a new tab using JavaScript, without using jQuery?

Here\'s the jQuery I

3条回答
  •  独厮守ぢ
    2020-12-30 11:18

    Pure JS:

    function externalLinks() {
      for(var c = document.getElementsByTagName("a"), a = 0;a < c.length;a++) {
        var b = c[a];
        b.getAttribute("href") && b.hostname !== location.hostname && (b.target = "_blank")
      }
    }
    ;
    externalLinks();
    

提交回复
热议问题