kakkalo kakkalo - 8 months ago 37
Javascript Question

How do I add target="_blank" to a link within a specified div?

Let's say I have the following code:

<div id="link_other">
<li><a href="http://www.google.com/">google</a></li>
<div class="some_class">
dsalkfnm sladkfm
<a href="http://www.yahoo.com/">yahoo</a>

In this case, the JavaScript would add
to all links within the div

How can I do that using JavaScript?

/* here are two different ways to do this */
//using jquery:
  $('#link_other a').attr('target', '_blank');

// not using jquery
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 is prettier. :-)

You could also add a title tag to notify the user that you are doing this, to warn them, because as has been pointed out, it's not what users expect:

$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');