Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending HTML w/click event using jQuery

Tags:

html

jquery

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?

like image 406
mrblah Avatar asked Feb 25 '09 03:02

mrblah


People also ask

How append HTML data to div in jQuery?

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.

How do you append something in jQuery?

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.

What is difference between append and HTML in jQuery?

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.

How do you append to an HTML file?

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')


1 Answers

What about :

$("#myID").click(
  function () {
     var someText = "my dynamic text";
     var newDiv = $("<div>").append(someText).click(function () { alert("click!"); });
     $(this).append(newDiv);
  }
)
like image 146
fulmicoton Avatar answered Sep 19 '22 01:09

fulmicoton