Reputation: 50587
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?
Upvotes: 2
Views: 2101
Reputation: 630627
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.
Upvotes: 6