Manipulating DOM Elements

Problem

I want to dynamically add DOM elements to my page.

Solution

You can use most of the JavaScript calls that work outside of Facebook to make programmatic changes to the DOM:

function addNewDiv(){
    var parentDiv = document.getElementById('parentDiv');

    // Appending a child
    var firstDiv = document.createElement('div');
    firstDiv.setId('appendedChild');
    firstDiv.setStyle('color', 'black');
    firstDiv.setTextValue('This div rocks!');
    parentDiv.appendChild(firstDiv);

    // Insert before
    var secondDiv = document.createElement('div');
    secondDiv.setStyle('color', 'red');
    secondDiv.setTextValue('This div rocks more!');
    parentDiv.insertBefore(secondDiv, firstDiv);

    // Remove the first div
    parentDiv.removeChild(firstDiv);

    // Clone the second node
    var thirdDiv = secondDiv.cloneNode();
    thirdDiv.setStyle('color', 'blue');
    thirdDiv.setTextValue('This is the third div to be created.');
    parentDiv.appendChild(thirdDiv);
}

Assuming you have a div in your HTML with the id parentDiv when you run the script, the end result will have it contain the text:

This div rocks more!
This is the third div to be created.

(with the text in the appropriate colors), along with anything else it might have contained already.

Although appendChild(), insertBefore(), removeChild(), and cloneNode() all work the same way they do off-Facebook, you’ll run into problems with many of the other JavaScript object manipulation functions. Most of the ones you’ve come to know and love are available, but they’ve been ...

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.