Use append() to add text/html to an element with jQuery
jQuery's function append() can be used to add text or html to an element. It's very easy to use and this post shows some example code and has a working example where you can type in some text that will be appended to a div.
The following is the HTML for the example:
<div id="example"> Example div </div>
It's easy to append text into this div using append() as shown below. It will append the text directly before the closing </div> tag. This example would add "this text was appended" to the above div:
$('#example').append("this text was appended");
And here's a working example. Type some text into the textarea, click the button and it will be added to the example div. The example below has a grey border around it to show where the div is. The text in the textarea can also contain html.
The above example will not work if you are reading this in a feed reader. Please click through to view this in a web browser if this is the case.
The .example-default-value part is explained in an earlier post about how to change the default text value on focus with jQuery.
- Running a function with jQuery when the window is resized (Tuesday, August 25th 2009)
- Changing the default text value on focus with jQuery (Friday, May 29th 2009)
- Find the index of the element that was clicked with jQuery (Tuesday, May 19th 2009)
- Clear upload file input field with jQuery (Sunday, May 10th 2009)