views:

29

answers:

1

I tried: $('#canvas').append('<div class="tile"></div>').css({left: leftPos, top: topPos});, but that sets the style of #canvas rather than the appended element.

I then tried: $('#canvas').append(('<div class="tile"></div>').css({left: leftPos, top: topPos}));, but that gives the error "Object <div class="tile"></div> has no method 'css'".

How can I add the element and set its style at the same time?

+3  A: 

You can do it like this:

$('<div class="tile"></div>').css({left: leftPos, top: topPos})
                             .appendTo('#canvas');

This creates the element, styles it, then uses .appendTo() to put it in the same place.

Alternatively, if you're using jQuery 1.4, you can specify the properties, including CSS when you create it, like this:

$('<div />', { class:'title', css: {left: leftPos, top: topPos}})
   .appendTo('#canvas');​

For more on this method, look at the jQuery() documentation, specifically the jQuery(html,props) section.

Nick Craver
Would this be the best way to do it? `$(document.createElement('div')).css({left: leftPos, top: topPos}).addClass('tile').appendTo('#canvas');`
Acorn
@Acorn - That's equivalent too...it's whatever style is most pleasing to your eyes I suppose :) Unless you're creating a **lot** of these, there's not much of a performance difference.
Nick Craver