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?
Bear in mind that doing this is considered bad practice in general by web developers and usability experts. Jakob Nielson has this to say about removing control of the users browsing experience:
I believe this is the rationale for the target attribute being removed by the W3C from the XHTML 1.1 spec.
If you're dead set on taking this approach, Pim Jager's solution is good.
A nicer, more user friendly idea, would be to append a graphic to all of your external links, indicating to the user that following the link will take them externally.
You could do this with jquery:
I use this for every external link:
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:
Inline:
Using jQuery:
Use this for every external link