views:

410

answers:

4

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?

A: 

This can be accomplished pretty easily with Jquery. You would add this to the onload:

$("div a[href^='http']").each(function() {
  $(this).attr("alt",altText);
  var oldClassAttributeValue = $(this).attr("class");
  if(!oldClassAttributeValue) {
   $(this).attr("class",newClassAttributeValue);
  }
});

You could modify this to add text. Class can also be modified using the css function.

Josh
+2  A: 

I think something like this could be a starting point:

var links = document.getElementsByTagName("a"); //use div object here instead of document
for (var i=0; i<links.length; i++)
{
   if (links[i].href.substring(0, 5) == 'https')
   {
      links[i].setAttribute('title', 'abc');
      links[i].setAttribute('class', 'abc');
      links[i].setAttribute('className', 'abc');
   }
}

you could also loop through all the A elements in the document, and check the parent to see if the div is the one you are looking for

Minor optimisation: `for (var i=0, n<links.length; i<n; ++i)`
Krzysztof Sikorski
Presumably typo: ‘n=links.length’ in the initialisation clause. Alternative optimisation when iteration order is unimportant: ‘for (var i= links.length; i-->0;)’
bobince
A: 

My (non-framework) approach would be something along the lines of:

window.onload = function(){
   targetDiv = document.getElementById("divName");
   linksArray = targetDiv.getElementsByTagName("a");
   for(i=0;i=linksArray.length;i++){
      thisLink = linksArray[i].href;
      if(thisLink.substring(4,0) = "http"){
         linksArray[i].className += "yourcontent";  //you said append so +=
         linksArray[i].alt += "yourcontent";
             } 
       }
   }

This is not tested but I would start like this and debug it from here.

mike nvck
+1  A: 

This one is tested:

<style type="text/css">
.AddedClass
{
  background-color: #88FF99;
}
</style>
<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))
      continue;
    if (links[i].className != undefined)
    {
      links[i].className += ' AddedClass';
    }
    else
    {
      links[i].className = 'AddedClass';
    }
    if (links[i].title != undefined && links[i].title != '')
    {
      links[i].title += ' (outside link)';
    }
    else
    {
      links[i].title = 'Outside link';
    }
  }
}
</script>

<div id="Links">
<a name="_Links"></a>
<a href="/foo.asp">FOO</a>
<a href="ftp://FTP.org/FILE.zip">FILE</a>
<a href="http://example.com/somewhere.html"&gt;SomeWhere&lt;/a&gt;
<a href="http://example.com/somewhere2.html" class="Gah">SomeWhere 2</a>
<a href="http://example.com/somewhere3.html" title="It goes somewhere">SomeWhere 3</a>
<a href="https://another-example.com/elsewhere.php?foo=bar"&gt;ElseWhere 1</a>
<a href="https://another-example.com/elsewhere.php?foo=boz" class="Doh">ElseWhere 2</a>
<a href="https://another-example.com/elsewhere.php?foo=rad" title="It goes elsewhere">ElseWhere 3</a>
<a href="deep/below/bar.asp">BAR</a>
<a href="javascript:ShowHideElement('me');">Show/Hide</a>
</div>

If you are on an account on a shared server, like http://big-server.com/~UserName/, 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 http://foo.my-server.com and http://bar.my-server.com marked as local.

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

PhiLho
But this seems to edit internal links also (links without http)?
It edits <a name=""> also.. that has not even an href
First remark: test it! href field is converted to full URL in all browsers I tested (IE6, FF3, Safari 3, Opera 9).Second remark: valid. Also for JS link. I updated the code.
PhiLho
Your fix did the job, now it works great. thanks :)