Here’s a jQuery object creation tip for a problem that I just ran into while coding:

This code works fine in Firefox 3, but not in IE 7:

jQuery(document.body).prepend('<div id="A"></div>');
var $A = jQuery('A');

alert($A.attr('id')); // undefined

So instead use the .prependTo function to instantly get the newly created object:

var $B = jQuery('<div id="B"></div>')
.prependTo(jQuery(document.body));

alert($B.attr('id')); // B

It is also cleaner looking.

Reblog this post [with Zemanta]