Another question - Grin with cat attached — LiveJournal
Previous Entry Next Entry
Another question Mar. 24th, 2004 04:50 pm
Anyone know how I access the "link" elements in the head of a HTML page via javascript?

URL references appreciated...

From: deliberateblank
Date: March 24th, 2004 - 03:13 pm (Link)

var links = document.getElementsByTagName('link');
for ( i=0 ; i<links.length ; i++ ) {
  alert("Rel: " & links[i].rel & " Href: " & links[i].href);
From: wechsler
Date: March 25th, 2004 - 03:31 am (Link)
Ah thanks, that seems to work; should let me build a useful favelet for RSS-detection. I was vaguely wondering if I could get into the header via DOM hierearchy navigation but can't see how that might work.
From: deliberateblank
Date: March 25th, 2004 - 04:34 am (Link)
That also should be possible. It ought not to be possible for the hierarchy to be anything other than HTML>HEAD>LINK, even with totally trashed markup. Unfortunately there's no getChildElementsByTagName, so you have to walk the tree. getElementsByTagName makes for shorter code though, and hopefully the DOM implementation holds a hash of element tag names internally making it not much slower. If the link elements turn out to be possible anywhere in the tree and you want them all then you'd need a recursive function to pull them out, which would almost certainly be slower than getElementsByTagName.

var eHtml = document.documentElement;
var eI = eHtml.firstChild;
while (eI) {
  if (eI.tagName=="HEAD") {
    var eJ = eI.firstChild;
    while (eJ) {
      if (eJ.tagName=="LINK") {
        alert("Rel: " & eJ.rel & " Href: " & eJ.href);
      eJ = eJ.nextSiblink;
  eI = eI.nextSibling;