Creating HTML elements with CSS classes in jQuery : IE surprise.

May 4, 2011 by alex


Let’s say you’ve got an HTML snippet like this, which you want to add a new element to.

<div id="test"></div>

You can easily add new elements.

jQuery('<span>').appendTo( '#test');


You might also want to add a CSS class also.

jQuery('<span class="foo">').appendTo( '#test' );

But be warned! This fails silently in IE7 and IE8! There’s no error raised, but no element is created or added to test div.

A Workable Alternative

jQuery( '<span>' ).addClass( 'foo' ).appendTo( '#test' );

seems to work just fine, though.

☙ ☙ ☙