I want to append some HTML inside this div, and the HTML has to have a click event on it also.
<div id="myID">
<p>hello, world!</p>
</div>
I want to insert a new div inside of the above div, and I want a click event on the new HTML I insert there. There will be some dynamic text inside the new div so it has to by dynamically created.
How can it be done?
Add New HTML Content append() - Inserts content at the end of the selected elements. prepend() - Inserts content at the beginning of the selected elements. after() - Inserts content after the selected elements. before() - Inserts content before the selected elements.
jQuery append() Method The 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.
html() will completely replace the content inside the tag that the selector corresponds to. $('#'). append() will just append to the end of the content inside the tag.
HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')
What about :
$("#myID").click(
function () {
var someText = "my dynamic text";
var newDiv = $("<div>").append(someText).click(function () { alert("click!"); });
$(this).append(newDiv);
}
)
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