자바스크립트를 사용하여 새 창에서 열도록 target 속성에 _blank 추가하기 [자체 정리용]

워드프레스 정보를 제공하는 블로그 Avada 2018. 9. 19. 03:34 • 댓글:

jQuery를 사용하면 target="_blank"를 추가하는 것이 매우 간단하다. 가령 다음 스크립트를 사용하면 내부 링크(내 사이트 링크)를 제외한 외부 링크에 target="_blank"를 추가할 수 있다.

$('a[href^="http://"]').not('a[href*=gusdecool]').attr('target','_blank');

또는

$('a[href^=http]:not([href^=http://www.gusdecool.com],[href^=http://gusdecool.com])')
    .add('a[href^=www]:not([href^=www.gusdecool.com])')
        .attr('target','_blank');
// 출처: https://stackoverflow.com/questions/7901679/jquery-add-target-blank-for-outgoing-link

javascript를 사용하려는 경우...

var linkList = document.querySelectorAll('#id a, .class a');

 

for(var i in linkList){
 linkList[i].setAttribute('target', '_blank');
}

다음과 같은 방법도 참고할 만하다.

window.onload = function(){
  var anchors = document.getElementById('link_other').getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    anchors[i].setAttribute('target', '_blank');
  }
}

이것을 jQuery로 구현하면 더 간단하다.

$(document).ready(function(){
  $('#link_other a').attr('target', '_blank');
});
// 출처: https://stackoverflow.com/questions/804256/how-do-i-add-target-blank-to-a-link-within-a-specified-div

참고할 만한 사이트:

  • https://www.sitepoint.com/community/t/change-link/236873/6
  • http://jywebdesign.com/change-href-using-javascript/
  • http://www.ronvangorp.com/change-link-url-with-javascript/
  • https://stackoverflow.com/questions/15385207/how-to-change-href-attribute-using-javascript-after-opening-the-link-in-a-new-wi/15385332

참고: