after 2 hours of searching I decided to ask my question.
I have a div:
I want to add a div inside th
It's just the wrong order
var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$('#box').append(e);
e.attr('id', 'myid');
Append first and then access/set attr.
You're overcomplicating things:
var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
e.attr('id', 'myid');
$('#box').append(e);
For example: http://jsfiddle.net/ambiguous/Dm5J2/
Why not go even simpler with either one of these options:
$("#box").html('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
Or, if you want to append it to existing content:
$("#box").append('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
Note: I put the id="myid"
right into the HTML string rather than using separate code to set it.
Both the .html()
and .append()
jQuery methods can take a string of HTML so there's no need to use a separate step for creating the objects.
var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);