Friday, 15 February 2013

Save all meta tags name and value to an object using JavaScript -



Save all meta tags name and value to an object using JavaScript -

i need read meta tags on specific page , store each meta name , content values in datalayer array used google tag manager.

i want fetch meta tags want able force each value in array accordingly.

i have next code don't think best way if have 20-30 meta tags.i hope can help me improve code!!

<html> <head> <title> test metas</title> <meta name="abc" content="dummy"/> <meta name="def" content="dummy"/> <meta name="jhk" content="dummy"/> </head> <body> <script type="text/javascript" charset="utf-8"> function gtmmeta(name) { var metas = document.getelementsbytagname('meta'); (i=0; i<metas.length; i++) { if (metas[i].getattribute('name') == name) { homecoming metas[i].getattribute('content'); } } homecoming ''; } datalayer = [{}]; if (gtmmeta('abc') !=''){ datalayer.push({'cmsname': gtmmeta('abc')}) }; if (gtmmeta('def') !=''){ datalayer.push({'transactiontotal': gtmmeta('def')}); } if (gtmmeta('jhk') !=''){ datalayer.push({'market': gtmmeta('jhk')}); } </script> </body> </html>

to save having through each <meta> every time, 1 way set name/content pairs object.

var metaobj = {}, m = document.head.getelementsbytagname('meta'), = m.length; while (i--) { // looping downwards result in same behaviour stopping @ 1st metaobj[m[i].name] = m[i].content; }

and take want straight object

if (metaobj['abc']) { datalayer.push({'cmsname': metaobj['abc']}); }

you automate these too, looping on sec object, similar suggested manishearth

var metainterest = {'abc':'cmsname','def':'transactiontotal', 'jhk':'market'}, o; (i in metainterest) if (metainterest.hasownproperty(i) && metaobj[i]) o = {}, o[metainterest[i]] = metaobj[i], datalayer.push(o);

javascript

No comments:

Post a Comment