Skip to main content

In our several previous jQuery examples we were focused to accessing DOM elements and getting their content. In this article we're going to show you how actually to change a element's content.

Below is a part of a HTML page that contains div with id = "testdiv" and a couple of other elements placed inside it:

<div id="testdiv">
    jQuery example
</div>

For changing content we can use a couple of jQuery functions:

.text(TEXT) - for setting plain text

.html(HTML) - for setting HTML code inside other element

- Advertisement -
- Advertisement -

Using text() function

For example, if we want to change "jQuery example" to "jQuery library example" in the example above we'll use the following code:

$(document).ready(function() {
    $('#testdiv').text('jQuery library example');
});

Using .html() function

However, we could want to display our text inside h1 tags; so in this case we'll use jQuery html function:

$(document).ready(function() {
    $('#testdiv').html('<h1>jQuery library example</h1>');
});

If we use this code with text() function the h1 tags will be treated as text and therefore displayed, they will not be considered as HTML code.

In short, difference between jQuery text() and html() function is that jQuery.html() treats the string as HTML, jQuery.text() treats the content as text.

- Advertisement -