[thelist] Adding META tag via the DOM if not already present (Javascript)

Dave Stevens evolt at davestevens.co.uk
Tue Jan 29 09:24:44 CST 2008


Hi all,

I am attempting to add two meta tags, required by the company's chosen 
Metrics solution, to the head of a page if they are not already present. 
I'm trying to do this through javascript and I've come across some 
difficulties.

The issue I'm having is in determining whether the META tags in question 
already exist - this is what I'm doing now:

  var metaTags = document.getElementsByTagName("meta");
  var i;
 
  if (metaTags.length > 0) {
    for (i in metaTags) {
      if (metaTags[i].hasAttributes) {
          /* This catches Firefox & Opera */         
          if (metaTags[i].attributes[1].nodeValue == "DCSext.wt_m" || 
metaTags[i].name == "DCSext.wt_m") {
            hasWTM1 = true;
          } else if (metaTags[i].attributes[1].nodeValue == 
"DCSext.wt_ml" || metaTags[i].name == "DCSext.wt_mle") {
            hasWTM2 = true;
          }
      } else {
        /* This catches IE & Safari */
       
        /* do the test for IE */
        if (metaTags[i].name == "DCSext.wt_mag") {
            hasWTM1 = true;       
        } else if (metaTags[i].name == "DCSext.wt_maglocale") {
            hasWTM2 = true;         
        }
      }
    }
  }


My first problem is that that bit of code is horrendous. However, 
Firefox gives me a "getAttribute is not a function" if I use 
metaTags[i].getAttribute("name") and will only respond to 
metaTags[i].attributes[1].nodeValue - though I found that Peter Paul 
Koch's quirksmode.org says never to use attributes[index].

metaTags[i].name works in Opera and Internet Explorer. Safari (on 
Windows) won't respond to any of the above.

Can anyone help me out and point me down a good route for detecting a 
specific meta tag in a document? The pages this will be used on may have 
multiple other meta tags or no meta tags.

Thanks,
Dave 



More information about the thelist mailing list