Use append() to add text/html to an element with jQueryUse append() to add text/html to an element with jQuery

Posted June 5th, 2009 in Javascript

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.

Example div

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 full HTML and Javascript for the above working example is as follows:

<div id="example" style="border: 1px solid rgb(204, 204, 204); margin: 5px 0pt; padding: 5px;">Example div</div>
<form>
    <div><textarea class="example-default-value" id="example-textarea" style="width: 400px; height: 50px;">Type some text in here to be appended</textarea></div>
    <div><input type="button" value="Append" onclick="example_append()" /></div>
</form>
<script language="javascript">
$('.example-default-value').each(function() {
    var default_value = this.value;
    $(this).focus(function() {
        if(this.value == default_value) {
            this.value = '';
        }
    });
    $(this).blur(function() {
        if(this.value == '') {
            this.value = default_value;
        }
    });
});
function example_append() {
    $('#example').append($('#example-textarea').val());
}
</script>

The .example-default-value part is explained in an earlier post about how to change the default text value on focus with jQuery.

Related posts:

Comments

blog comments powered by Disqus