O'Reilly logo

Facebook Cookbook by Jay Goldman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required