Replace Inner HTML with jQuery

Replacing the inner HTML of an element using jQuery is a fundamental DOM manipulation task most commonly accomplished with the .html() method. This article provides a concise guide on how to use jQuery's .html() method to overwrite an element's contents with new markup, including syntax examples, dynamic updates, and the difference between updating HTML versus plain text.

The .html() Method

To replace the inner HTML of any targeted element, select the element using a standard jQuery selector and pass the new HTML string into the .html() function.

// Target by ID and replace its inner HTML
$('#targetElement').html('<p>This is the new content.</p>');

When this code executes, all existing child nodes, text, and markup inside #targetElement are immediately removed and replaced with the new paragraph element.

Using a Function to Return New HTML

The .html() method can also accept an anonymous or callback function. This is useful when you need to calculate new content based on the element's current index or existing HTML.

$('div.item').html(function(index, oldHtml) {
    return '<span>Item #' + (index + 1) + ':</span> ' + oldHtml;
});

The function receives two arguments: the index position of the element within the selection and the current inner HTML. Whatever string the function returns becomes the new inner HTML.

Replacing Inner HTML vs. Inner Text

It is important to distinguish between .html() and .text():

  • .html(): Parses the provided string as HTML, rendering tags such as <b>, <div>, or <a>.
  • .text(): Treats the provided string as literal plain text, automatically escaping HTML entities.

If you pass HTML tags to .text(), they will be displayed as raw text rather than being rendered as DOM elements:

// Renders a bold text element
$('#target').html('<b>Bold Text</b>');

// Displays the literal string "<b>Bold Text</b>" to the user
$('#target').text('<b>Bold Text</b>');

Clearing the Inner HTML

To completely remove the contents of an element without inserting new content, you can either pass an empty string to .html() or use the specialized .empty() method, which also safely removes attached event handlers and cached data from child elements:

// Method 1: Using .html()
$('#targetElement').html('');

// Method 2: Using .empty() (recommended for clearing)
$('#targetElement').empty();