jQuery html() and text() Methods

The html() and text() methods let you read or change the content inside HTML elements. They look similar but behave very differently. Choosing the right one protects your page from security risks and ensures content displays correctly.

The html() Method

The html() method gets or sets the HTML content inside an element. It reads and writes raw HTML — tags are interpreted and rendered.

Get HTML Content

HTML:
<div id="box"><p>Hello <strong>World</strong></p></div>

jQuery:
var content = $("#box").html();
// content = "<p>Hello <strong>World</strong></p>"

Set HTML Content

$("#box").html("<p>New <em>content</em> here</p>");
// The old content is replaced with the new HTML
// The <em> tag is rendered as italic text

The text() Method

The text() method gets or sets the plain text inside an element. Any HTML tags are treated as plain text — they are not rendered, they show up as characters on screen.

Get Text Content

HTML:
<div id="box"><p>Hello <strong>World</strong></p></div>

jQuery:
var content = $("#box").text();
// content = "Hello World"   (only the visible text, no tags)

Set Text Content

$("#box").text("<p>New content here</p>");
// The tags are NOT rendered — they display as visible characters:
// Output on screen: <p>New content here</p>

Diagram: html() vs text() Difference

  html():
  ┌────────────────────────────────────┐
  │ Input:  "Hello <b>World</b>"       │
  │ Output: Hello World                │  ← "World" appears bold
  └────────────────────────────────────┘

  text():
  ┌────────────────────────────────────┐
  │ Input:  "Hello <b>World</b>"       │
  │ Output: Hello <b>World</b>         │  ← tags appear as text
  └────────────────────────────────────┘

Getting vs Setting — Same Method, Two Modes

Both html() and text() work in two modes:

  • No argument → getter (reads the current content)
  • With argument → setter (replaces the current content)
// Getter mode
var currentHtml = $("div").html();  // reads content of FIRST matched element
var currentText = $("div").text();  // reads content of ALL matched elements combined

// Setter mode
$("div").html("<b>New</b>");  // sets HTML in ALL matched elements
$("div").text("New");            // sets plain text in ALL matched elements

An Important Getter Difference

html() returns content from the first matched element only. text() returns the combined text of all matched elements.

HTML:
<p>First paragraph</p>
<p>Second paragraph</p>

$("p").html()  → "First paragraph"         (first <p> only)
$("p").text()  → "First paragraphSecond paragraph"  (both combined)

Security: Why text() is Safer than html()

When you display content that comes from a user (like a comment or search input), always use text(). The html() method renders tags — a malicious user could inject harmful scripts.

// Unsafe — user input could contain <script> tags:
$("#output").html(userInput);

// Safe — tags are shown as plain characters, not executed:
$("#output").text(userInput);

Practical Example: Live Heading Editor

HTML:
<input id="titleInput" type="text" placeholder="Enter heading" />
<button id="updateBtn">Update Heading</button>
<h2 id="mainTitle">Original Heading</h2>

jQuery:
$(document).ready(function() {
    $("#updateBtn").click(function() {
        var newTitle = $("#titleInput").val();
        $("#mainTitle").text(newTitle);  // safe — no HTML injection possible
    });
});

Using html() to Build Dynamic Content

$(document).ready(function() {
    var products = [
        { name: "Laptop", price: "₹50,000" },
        { name: "Mouse",  price: "₹800" },
        { name: "Keyboard", price: "₹1,500" }
    ];

    var html = "<ul>";
    $.each(products, function(i, p) {
        html += "<li><strong>" + p.name + "</strong> — " + p.price + "</li>";
    });
    html += "</ul>";

    $("#productList").html(html);
});

Quick Comparison Table

Featurehtml()text()
Tags renderedYesNo (shown as text)
Getter scopeFirst matched elementAll matched elements
Security with user inputRiskySafe
Use forBuilding markupDisplaying plain content

Quick Summary

  • html() reads or writes HTML — tags are rendered in the browser.
  • text() reads or writes plain text — tags appear as visible characters.
  • No argument = getter mode; with argument = setter mode.
  • Use text() when showing user-provided content to prevent script injection.
  • Use html() when you need to insert HTML markup dynamically.

Leave a Comment

Your email address will not be published. Required fields are marked *