jQuery Method to Get Inner HTML of an Element

This article explains how to retrieve the inner HTML of an element using jQuery. In web development, accessing child elements and text inside a container is a common task. You will learn the specific jQuery method used for this operation, its syntax, a practical code example, and how it compares to retrieving plain text.

The primary jQuery method used to get the inner HTML of an element is .html(). When called without arguments on a jQuery selection, it reads and returns the HTML contents of the first element in the matched set, including any HTML tags and text nodes.

Syntax

var content = $(selector).html();

Example Usage

Consider the following HTML markup:

<div id="container">
    <p>Hello <strong>World</strong>!</p>
</div>

To retrieve the HTML markup inside #container, use the .html() method:

$(document).ready(function() {
    var innerContent = $("#container").html();
    console.log(innerContent);
});

Output:

<p>Hello <strong>World</strong>!</p>

.html() vs .text()

It is important to distinguish .html() from the .text() method:

  • .html(): Returns the inner HTML markup, preserving tags like <p>, <strong>, and <span>. It relies on the browser's native innerHTML property.
  • .text(): Strips all HTML tags and returns only the combined text content of the matched elements.

For the example above, calling $("#container").text() would return Hello World! instead of the full HTML markup.

Setting Inner HTML

The .html() method also acts as a setter. If you pass a string containing HTML into the method, it will overwrite the current content of the selected element:

$("#container").html("<span>New dynamic content</span>");