t q t q - 12 days ago 6
Javascript Question

dynamically change metadata - no jquery

I found this link on changing meta data using jQuery

$("meta[property='og\\:title']").attr("content", result.title);
,

but is it possible to do it with straight javascript?

I know you can access an items attribute like so
document.getElementById("myimage").setAttribute("src","another.gif")
,

but i cant seem to change metadata.

I am trying to dynamically alter metadata for facebook.

<meta property="fb:app_id" content="*************" />
<meta property="og:url" content="" />
<meta property="og:site_name" content="" />
<meta property="og:type" content="" />
<meta property="og:image" content="" />
<meta property="og:title" content="" />
<meta property="og:description" content="" />

Answer

Assuming that the meta tag you want to modify is first in the list, you can do:

var metaFB = document.getElementsByTagName("meta")[0];

Now you can modify the attributes to your liking.

Edit: As @Jamiec points out, even if it's not first in the list, you can specify where. If you don't know where, you can iterate through the elements check the attributes:

var metaList = document.getElementsByTagName("meta");
for (var i = 0; i < metaList.length; i++) {
    if (metaList[i].getAttribute("property") == "fb:app_id") {
        metaList[i].content = "somenewcontent";
    }
}
Comments