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

Ken Snyder kendsnyder at gmail.com
Tue Jan 29 09:56:40 CST 2008

Dave Stevens wrote:
> 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.
> ...
> 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 

If the attribute access is not consistent across browsers, you could 
resort to a hackish but effective use of innerHTML--see below.

- Ken Snyder

function getDocumentMeta() {
    var source = document.getElementsByTagName('head')[0].innerHTML;
    var pattern1 = /<meta[^>]+name="([^"]+)"[^>]+content="([^"]+)"[^>]*>/i;
    var pattern2 = /<meta[^>]+content="([^"]+)"[^>]+name="([^"]+)"[^>]*>/i;
    var match, meta = {};
    while (source.length > 0) {
        if (match = source.match(pattern1)) {
            meta[match[1]] = match[2];
            source = source.slice(match.index + match[0].length);
        } else if (match = source.match(pattern2)) {
            meta[match[2]] = match[1];
            source = source.slice(match.index + match[0].length);       
        } else {
            source = '';
    return meta;
var meta = getDocumentMeta();
if (!meta['DCSext.wt_m']) {
  // add the meta

More information about the thelist mailing list