jQuery jQuery.parseHTML() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
HTML parsing

What You’ll Learn

The jQuery.parseHTML() utility converts an HTML string into an array of DOM nodes you can inspect or append. This tutorial covers the official jQuery API demo, element fragments, whitespace trimming, the keepScripts flag, security considerations, and comparisons with $(htmlString).

01

Syntax

$.parseHTML(s)

02

Array out

DOM node list

03

Context

Document scope

04

Scripts

Off by default

05

Trim first

Skip edge text

06

Security

Sanitize input

Introduction

Dynamic web apps often receive HTML snippets from templates, AJAX responses, or user input. Before inserting that markup into the page, you may want to parse it into real DOM nodes, inspect what was created, and control whether scripts are included.

jQuery added jQuery.parseHTML() (also written $.parseHTML()) in version 1.8 for exactly that job. It uses native browser parsing under the hood and returns a plain array — not a jQuery collection — so you decide when and where nodes enter the live document.

Understanding the jQuery.parseHTML() Method

jQuery.parseHTML(data) takes an HTML string and produces an array of nodes. Entries can be elements (<p>), text nodes (plain text without tags), or comments. The nodes are detached until you append them with .append(), .html(), or similar APIs.

By default, keepScripts is false, so <script> tags are stripped from the result. That makes parseHTML a safer parsing step than blindly injecting HTML — though you must still treat untrusted strings as a security risk.

💡
Beginner Tip

Think of parseHTML as a factory that builds DOM pieces offline. Nothing appears on the page until you attach the returned nodes to an element in the document.

📝 Syntax

General form of jQuery.parseHTML:

jQuery
jQuery.parseHTML( data [, context ] [, keepScripts ] )
// or
$.parseHTML( data [, context ] [, keepScripts ] )

Parameters

  • data — the HTML string to parse into DOM nodes.
  • context — optional document element used as the parsing context (defaults to a detached document in jQuery 3.0+ when omitted).
  • keepScripts — optional boolean; when true, <script> elements are included in the result (default false).

Return value

  • An array of DOM nodes parsed from the string.

Official jQuery API workflow

jQuery
var str = "hello, my name is jQuery.";
var html = $.parseHTML(str);
$("#log").append(html);

⚡ Quick Reference

GoalCode
Parse HTML string$.parseHTML(str)
Append parsed nodes$(parent).append(nodes)
Avoid edge whitespace nodes$.parseHTML(str.trim())
Include script tags$.parseHTML(str, null, true)
Scripts execute on parse?No — even with keepScripts
Return typeArray of DOM nodes

📋 $.parseHTML vs $(html) vs innerHTML

Three ways to turn strings into DOM — different safety and return shapes.

parseHTML
Node[]

Detached array; scripts off by default

$()
jQuery

Collection; live injection risks

innerHTML
assign

Native; parses in place

Security
sanitize

Never trust raw user HTML

Examples Gallery

Example 1 follows the official jQuery API demo. Use DevTools or the Try-it links to run each snippet interactively.

📚 Getting Started

Parse plain text and HTML into detached DOM nodes.

Example 1 — Official jQuery API Demo

Parse a plain text string, append the nodes, and list each node name — matching the jQuery documentation.

jQuery
var str = "hello, my name is jQuery.";
var html = $.parseHTML(str);
var nodeNames = [];

$.each(html, function (i, el) {
  nodeNames.push(el.nodeName);
});

console.log(nodeNames.join(", ")); // #text
Try It Yourself

How It Works

A string without HTML tags still produces a text node. The returned array has one entry whose nodeName is #text. Appending it to a div displays the sentence on the page.

📈 Practical Patterns

Fragments, trimming, script handling, and controlled insertion.

Example 2 — Parse an HTML Fragment with Multiple Elements

Parse a snippet containing two elements and inspect the node names in order.

jQuery
var markup = "<p>Hello</p><span>World</span>";
var nodes = $.parseHTML(markup);

var names = $.map(nodes, function (el) {
  return el.nodeName;
});

console.log(names.join(" → "));
// P → SPAN
Try It Yourself

How It Works

Each top-level tag in the fragment becomes one node in the array. Nested markup stays inside those elements. You can loop the array or pass it directly to .append().

Example 3 — Trim Before Parsing to Skip Edge Text Nodes

Leading and trailing whitespace can become extra #text nodes — trim the string first.

jQuery
var raw = "   <strong>Bold</strong>   ";

var withoutTrim = $.parseHTML(raw);
var withTrim    = $.parseHTML(raw.trim());

console.log("Without trim:", withoutTrim.length, "nodes");
console.log("With trim:", withTrim.length, "nodes");
Try It Yourself

How It Works

Without trimming, spaces before and after the tag become separate text nodes. The jQuery API recommends $.parseHTML($.trim(str)) or $.parseHTML(str.trim()) when you only want element nodes.

Example 4 — Default keepScripts: false Strips Script Tags

Script elements are excluded from the result unless you explicitly opt in.

jQuery
var snippet = '<p>Hi</p><script>alert("x")</script>';

var safe   = $.parseHTML(snippet);
var unsafe = $.parseHTML(snippet, null, true);

console.log("Default count:", safe.length);    // 1 (P only)
console.log("keepScripts:", unsafe.length);    // 2 (P + SCRIPT)
Try It Yourself

How It Works

Parsing does not execute scripts — even with keepScripts: true. Scripts can run after you insert nodes into the live document, so never enable keepScripts for untrusted HTML.

Example 5 — Parse, Inspect, Then Append to the Page

Build UI from a template string only after verifying the parsed structure.

jQuery
var template = '<article class="card"><h2>Title</h2><p>Body</p></article>';
var nodes = $.parseHTML(template.trim());

// Inspect before inserting
var hasCard = nodes.length === 1 && nodes[0].className === "card";

if (hasCard) {
  $("#mount").empty().append(nodes);
  console.log("Card mounted");
}
Try It Yourself

How It Works

parseHTML lets you validate parsed nodes before they touch the DOM. That pattern is useful for templating pipelines where you filter unsafe attributes or strip disallowed tags before append.

🚀 Common Use Cases

  • AJAX HTML partials — parse server-rendered snippets before inserting into a container.
  • Template strings — convert markup templates to nodes for inspection or transformation.
  • Plugin rendering — build widget DOM offline, then append once structure is verified.
  • iframe context — pass an iframe’s document as context when parsing for that frame.
  • Security pipelines — walk parsed nodes and remove unsafe attributes before mount.
  • Text-only content — parse plain strings into text nodes for consistent append APIs.

🧠 How jQuery.parseHTML() Builds DOM Nodes

1

Receive HTML string

Optional trim removes leading/trailing whitespace text nodes.

Input
2

Native parse

Browser parsing runs in the chosen context document (detached in jQuery 3+).

Parse
3

Filter scripts

Unless keepScripts is true, <script> nodes are removed from the result.

Filter
4

Return node array

Detached nodes ready for inspection or .append() into the live page.

📝 Notes

  • Available since jQuery 1.8; context default changed in jQuery 3.0 for safer detached parsing.
  • Scripts in the HTML string do not execute during parse — only after insertion into a document.
  • Inline event attributes (like onclick) may still be a risk after injection — sanitize untrusted HTML.
  • Most jQuery HTML APIs can run scripts when strings are inserted; parseHTML is the controlled parsing step.
  • Return value is a plain array — wrap with $() if you need jQuery methods on the nodes.
  • For iframe documents, pass the iframe’s contentDocument as context.

Browser Support

jQuery.parseHTML() has been part of jQuery since 1.8+. It delegates to native DOM parsing and works wherever jQuery runs — all modern browsers and supported legacy environments with jQuery loaded.

jQuery 1.8+

jQuery jQuery.parseHTML()

Supported in jQuery 1.8, 2.x, and 3.x. Behavior is consistent across browsers because jQuery wraps native createContextualFragment / innerHTML parsing.

100% With jQuery loaded
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
jQuery.parseHTML() Universal

Bottom line: Safe to use in any jQuery project. Security depends on your input — sanitize HTML from users, URLs, or cookies before parsing and inserting into the page.

Conclusion

The jQuery.parseHTML() utility turns HTML strings into arrays of detached DOM nodes. Use it when you need to inspect markup before insertion, strip scripts by default, and control parsing context — especially in jQuery 3.0+ security-conscious workflows.

Always trim edge whitespace when needed, never trust raw user HTML, and prefer parsing with parseHTML over blind $(htmlString) injection when building safe rendering pipelines.

💡 Best Practices

✅ Do

  • Trim HTML strings before parsing when whitespace matters
  • Keep keepScripts false for untrusted content
  • Inspect parsed nodes before appending to the document
  • Sanitize or escape HTML from users and external sources
  • Use .append($.parseHTML(...)) for controlled insertion

❌ Don’t

  • Parse and inject unsanitized user HTML directly
  • Assume parseHTML executes or blocks all XSS vectors
  • Enable keepScripts: true on external markup
  • Forget that edge spaces become #text nodes
  • Confuse the returned array with a jQuery collection

Key Takeaways

Knowledge Unlocked

Five things to remember about jQuery.parseHTML()

Parse HTML offline, inject when ready.

5
Core concepts
📦 02

Array

Not jQuery

Return
🔒 03

No scripts

Default safe

Security
04

Trim

Skip edge text

Tip
05

Append

When verified

Pattern

❓ Frequently Asked Questions

jQuery.parseHTML(data, context, keepScripts) parses an HTML string and returns an array of DOM nodes — elements, text nodes, and comments — without inserting them into the page. You can append the array with .append() or inspect nodes before injection.
The jQuery API passes a plain text string to $.parseHTML(), appends the resulting nodes to a log div, and lists each node name (such as #text). It shows that even a string without angle brackets becomes a text node in the returned array.
Both can turn HTML strings into DOM content, but parseHTML returns a plain array of nodes and does not run scripts by default (keepScripts is false). jQuery's $(html) insertion paths are still subject to script injection when malicious HTML is appended to the live document. parseHTML is the safer parsing step when you need nodes first.
When keepScripts is false (the default), script elements in the HTML string are not included in the returned nodes. When true, script tags are parsed into the array — but scripts still do not execute until those nodes are inserted into a document. Never pass untrusted HTML with keepScripts true.
Leading and trailing whitespace in the HTML string can become text nodes in the parsed output. The jQuery API recommends passing the string through jQuery.trim() (or native trim()) first when you want to avoid extra whitespace text nodes at the edges.
When context is omitted, null, or undefined, jQuery 3.0+ uses a new detached document to parse HTML. That prevents inline event handlers in the string from firing during parsing. Once you inject the nodes into the live page, scripts and handlers can still run — always sanitize untrusted input.
Did you know?

jQuery 3.0 changed parseHTML so that when context is omitted, parsing happens in a new detached document. Inline event handlers in the HTML string no longer fire during parsing — giving sanitizers a chance to walk the node tree before anything reaches your live page. Injection into the document can still trigger behavior, which is why the API documentation stresses cleaning untrusted input.

Continue to jQuery.parseXML()

Learn how to parse XML strings and traverse them with jQuery find() and text().

parseXML() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful