Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  52] [ 7]  / answers: 1 / hits: 155612  / 15 Years ago, wed, april 29, 2009, 12:00:00

Let's say I have the following code:



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


In this case, the JavaScript would add target=_blank to all links within the div link_other.



How can I do that using JavaScript?


More From » hyperlink

 Answers
16
/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
$('#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.');

[#99629] Thursday, April 23, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daveon

Total Points: 749
Total Questions: 108
Total Answers: 87

Location: Malaysia
Member since Wed, May 11, 2022
2 Years ago
;