Javascript – Editing all external links with javascript


How can I go through all external links in a div with javascript, adding (or appending) a class and alt-text?

I guess I need to fetch all objects inside the div element, then check if each object is a , and check if the href attributen starts with http(s):// (should then be an external link), then add content to the alt and class attribute (if they don't exist create them, if they do exists; append the wanted values).

But, how do I do this in code?

Best Solution

This one is tested:

<style type="text/css">
  background-color: #88FF99;
<script type="text/javascript">
window.onload = function ()
  var re = /^(https?:\/\/[^\/]+).*$/;
  var currentHref = window.location.href.replace(re, '$1');
  var reLocal = new RegExp('^' + currentHref.replace(/\./, '\\.'));

  var linksDiv = document.getElementById("Links");
  if (linksDiv == null) return;
  var links = linksDiv.getElementsByTagName("a");
  for (var i = 0; i < links.length; i++)
    var href = links[i].href;
    if (href == '' || reLocal.test(href) || !/^http/.test(href))
    if (links[i].className != undefined)
      links[i].className += ' AddedClass';
      links[i].className = 'AddedClass';
    if (links[i].title != undefined && links[i].title != '')
      links[i].title += ' (outside link)';
      links[i].title = 'Outside link';

<div id="Links">
<a name="_Links"></a>
<a href="/foo.asp">FOO</a>
<a href="">FILE</a>
<a href="">SomeWhere</a>
<a href="" class="Gah">SomeWhere 2</a>
<a href="" title="It goes somewhere">SomeWhere 3</a>
<a href="">ElseWhere 1</a>
<a href="" class="Doh">ElseWhere 2</a>
<a href="" title="It goes elsewhere">ElseWhere 3</a>
<a href="deep/below/bar.asp">BAR</a>
<a href="javascript:ShowHideElement('me');">Show/Hide</a>

If you are on an account on a shared server, like, you might want to hard-code the URL to go beyond the top level. On the other hand, you might want to alter the RE if you want and marked as local.

[UPDATE] Improved robustness after good remarks...
I don't highlight FTP or other protocols, they probably deserve a distinct routine.