Modify prototype of a metatag object

297 Views Asked by At

I'm dynamically generating metatags. I'm able to append the properties of the object that are part of the metatag prototype by default. name, content and ID. But when I try to append something different to the object, say foo it doesn't append.

How do I add my own property so I can add to it in the same way I'm adding the name id and content in the example.

var headID = document.getElementsByTagName("head")[0];        
var metaNode = document.createElement('meta');
metaNode.name = "name"; //appends
metaNode.id = "id"; //appends
metaNode.content = "content"; //appends
metaNode.foo = "bar"; //doesn't append
headID.appendChild(metaNode);

result: <meta id="id" name="name" content="content">

want: <meta id="id" name="name" content="content" foo="bar">

3

There are 3 best solutions below

0
On BEST ANSWER

metaNode.setAttribute('foo', 'bar');

6
On

A more standards compliant way of doing this would be to prefix it with data-:

metaNode.setAttribute("data-foo", "bar");

Though, the result would be:

<meta id="id" name="name" data-foo="bar" />
0
On

When you add a property to a DOM object, some browsers will also add an attribute with the same name regardless of what it is (e.g. IE) others will only add the attribute if the name is the same as a standard attribute (e.g. Firefox).

If you really want to deal with non-standard attributes, use get/setAttribute, but it is a bit buggy in IE so only use it for non-standard attributes, use properties for everything else. And if you are adding non-standard properties, it is best to store them in a javascript object rather than modifying DOM objects (mostly because you might be stomping on standard DOM properties or those added by other code).

Also, DOM objects are host objects so might not like you adding non-standard properties (again, there's no spec that says they have to let you).

Lastly, there is no reason to believe that there is a meta element constructor, that it has a prototype or that instances of meta elements inherit from that prototype. Some browsers implement javascript-like prototype inheritance for DOM objects, others don't. There is nothing that says DOM objects must use prototype inheritance (and some don't).