Creating Elements Dynamically

Problem

I want to dynamically create DOM objects and pop them into my page.

Solution

Use document.createElement(), the same way that you would in traditional JavaScript.

Discussion

This is one of the things that doesn’t change in FBJS, so your knowledge of off-Facebook JavaScript can be applied directly.

One special exception to note: document.createElement() can be used to create FBML elements, but it is currently limited to <fb:swf> (not even <fb:flv> or <fb:silverlight> work). The call is basically the same:

var newFlash = document.createElement('fb:swf');

Once you’ve created your object and attached it to the DOM (using a call such as appendChild()), you will not be able to move it around the DOM, and it will be rendered by the FBML parser into a standard <embed> tag.

Get Facebook Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.