html and text Methods
html and text Methods: free step-by-step lesson with examples, common mistakes, and interview tips — part of jQuery Tutorial on Toolliyo Academy.
On this page
jQuery Tutorial · Lesson 11 of 100
html and text Methods
Setup & DOM → Events Effects AJAX → Perf & Integrate → Ship & Projects
Setup & DOM · 1 — Select · ~6 min · DOM Updates
What is this?
text() reads/writes plain text. html() reads/writes HTML markup. Prefer text() for untrusted strings.
Why should you care?
Updating labels and messages is daily QueryVerse work — XSS-safe habits matter.
See it live — copy this example
Examples include the jQuery 3.7 CDN. Paste into an HTML file or use Run Example to preview.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>QueryVerse</title>
<style>
body { font-family: system-ui, sans-serif; margin: 1.25rem; }
.box { padding: .75rem; border: 1px solid #ccc; border-radius: 8px; margin: .5rem 0; }
.muted { color: #666; }
button { margin-right: .35rem; margin-top: .35rem; }
</style>
</head>
<body>
<div id="panel" class="box">Old</div>
<button id="asText">Set text</button>
<button id="asHtml">Set html</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function () {
$('#asText').on('click', function () {
$('#panel').text('<b>safe</b> plain');
});
$('#asHtml').on('click', function () {
$('#panel').html('<b>bold</b> markup');
});
});
</script>
</body>
</html>
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- text escapes HTML.
- html parses tags.
- Never html() user input without sanitizing.
Practice next
- Click both buttons and compare.
- Read back with .text() and .html().
- Pass a function form: .text(function(i, old){...}).
- Append a span with html carefully.
- Use .empty() then text.
Remember
text = safe string. html = markup. Untrusted → text.
Flash message
Show server message in a banner.
Outcome: You choose text vs html deliberately.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!