after 2 hours of searching I decided to ask my question.
I have a div:
<div id="box"></div>
I want to add a div inside the above div using jQuery.
I tried (following code is inside a function):
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>'); $('div', e).attr('id', 'myid'); $("#box").append(e);
But accessing $("#myid")
is not working.
Any idea on how to add a div inside a div and be able to manipulate them?
First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the append() method to copy the element as its child.
Projects In JavaScript & JQuery The append (content) method appends content to the inside of every matched element, whereas the appendTo (selector) method appends all of the matched elements to another, specified, set of elements.
To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.
jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With