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

Lee Kowalkowski lee.kowalkowski at googlemail.com
Tue Jan 29 09:47:01 CST 2008


On 29/01/2008, Dave Stevens <evolt at davestevens.co.uk> wrote:
> 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.
>  var metaTags = document.getElementsByTagName("meta");
>  var i;
>
>  if (metaTags.length > 0) {
>    for (i in metaTags) {

You could never do this in Netscape, I'm wondering if this is true with Safari.

The for-in loop in IE6, will iterate through ['length',0,1,...]

In Firefox 2, it will iterate through [0, 1, ..., 'length', 'item', 'namedItem']

In Netscape, it'll not iterate through the collection at all, just
['item', 'length', 'namedItem'].

Your problem with Firefox might be that eventually it tries
metaTags['length'].getAttribute('name'), as length is a number,
there's no getAttribute function.

Have you tried a standard for loop?  for(var i = 0; i < metaTags.length; i++); ?

-- 
Lee



More information about the thelist mailing list