Avoiding Heartache When the DOM Changes

Problem

I’ve built an amazing piece of JavaScript that has suddenly stopped working because Facebook has changed the structure of the page!

Solution

Be careful when you architect your code so that you don’t build very specific DOM structures into it:

this.getElementByTagName('div')[1].getFirstChild()
.getLastChild().setStyle('color', 'white');

It’s a much better idea to assign everything on your page a unique id or to give all similar objects a shared class so that you can target them more specifically from your JavaScript.

Discussion

The statement just shown is fragile for at least two reasons:

  • It’s effectively chaining down to the last child of the first child of the second <div> on the page (remember that arrays in JavaScript are zero-indexed, so the first <div> would be [0]). You might inadvertently change your own markup and insert an element above what used to be the first child, or below what used to be the last one.

  • If you’re used to doing development in a more traditional environment, you might not run into too many circumstances in which the HTML in your page changes without you doing it. Consider what happens to your code when Facebook changes the way something like <fb:multi-friend-input> is actually output by the FBML parser. If Facebook adds an extra <div>, your count is now off.

All of this is not to suggest that you shouldn’t chain your JavaScript commands together. There are plenty of times when combining a few lines of code can help ...

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.