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

Christian Heilmann codepo8 at gmail.com
Wed Jan 30 01:31:27 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:

Probably the quickest way would be to do a regex check on innerHTML of
the HEAD element, then you neither need to worry about the browser
inconsistencies nor about the slowness of this approach.

Just include that at the end of the BODY as the head won't be ready if
you include it there:

      var head = document.getElementsByTagName('head')[0];
      var content = head.innerHTML;
      if(content.indexOf('name="DCSext.wt_m"') === -1 &&
         content.indexOf('name="DCSext.wt_maglocale"') === -1){
        // can not has metas KTHXBAI
        var meta = document.createElement('meta');
        meta.name = 'DCSext.wt_maglocale';
        meta.content = 'en-uk';
        // ... and so on ...


Chris Heilmann
Book: http://www.beginningjavascript.com
Blog: http://www.wait-till-i.com
Writing: http://icant.co.uk/

More information about the thelist mailing list