jQuery parseHTML() Method

Beginner
7 min read
Updated: Oct 2026
4 examples
Live preview

What Is parseHTML()?

jQuery.parseHTML(data [, context ] [, keepScripts ]) (alias $.parseHTML) turns an HTML string into an array of DOM nodes using native browser parsing (added in jQuery 1.8). Nodes stay detached until you append them.

Remember
$.parseHTML(htmlString)  → Array of DOM nodes

nodes = $.parseHTML("<p>Hi</p><span>Go</span>")
// → [ <p>, <span> ]

$("#box").append(nodes)   // now visible on the page
NeedUse
Parse HTML text$.parseHTML(str)
Skip edge whitespace nodes$.parseHTML(str.trim())
Parse XML feeds$.parseXML(str)
Parse JSON strings$.parseJSON(str)

How to Use parseHTML()

Parse offline, inspect the node array, then append only what you trust.

  1. Start with an HTML string (fragment, template, or plain text).
  2. Optionally .trim() the string to drop edge whitespace text nodes.
  3. Call $.parseHTML(html) to get a plain array of nodes.
  4. Inspect or filter nodes, then $(target).append(nodes) when ready.
PieceRequired?Role
dataYesHTML string to parse
contextNoDocument used as parse context (detached doc in 3.0+ if omitted)
keepScriptsNoInclude <script> nodes when true (default false)
Return—Array of DOM nodes (not a jQuery object)

Pseudocode

Pseudocode
function parseHTML(data, context, keepScripts):
    // native HTML fragment parse
    nodes = parse data into DOM nodes
    if keepScripts is false:
        remove script elements from nodes
    return nodes   // plain Array

// Typical jQuery flow:
html  = markup.trim()
nodes = $.parseHTML(html)
$("#mount").append(nodes)

Cheat Sheet

Keep these facts handy while parsing HTML with jQuery.

TopicDetail
SyntaxjQuery.parseHTML(data [, context ] [, keepScripts ])
SincejQuery 1.8
InputHTML String
OutputArray of DOM nodes
ScriptsStripped unless keepScripts is true
Trim helper$.trim(str) or str.trim()
XML sibling$.parseXML()
Append nodes.append(nodes)

Live Preview

Pick a sample string, parse it with $.parseHTML, and inspect the node list.

Browser demo of $.parseHTML() — same ideas as the examples below.

Result
sample = Plain text
nodes → 1
names → #text

jQuery Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Official Demo (Plain Text)

Official jQuery API pattern: even plain text becomes a node.

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

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

console.log(html.length);       // 1
console.log(names.join(", "));  // "#text"
Try It Yourself

How It Works

  1. Input. The string has no tags — it is still valid input for parseHTML.
  2. Parse. $.parseHTML(str) returns an array with one text node.
  3. Inspect. el.nodeName for a text node is "#text".
  4. Use. You can .append(html) later to put that text into the page.

Example 2 — Parse an HTML Fragment

Turn a small markup string into real elements, then mount them.

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"
$("#mount").append(nodes);
Try It Yourself

How It Works

  1. Fragment. Two sibling tags become two top-level nodes in the array.
  2. Map. $.map collects each nodeName (P, SPAN).
  3. Append. .append(nodes) inserts the array into #mount.
  4. Tip. The return value is a plain array — wrap with $(nodes) only if you need jQuery methods on the set.

Example 3 — Trim Edge Whitespace

Leading/trailing spaces can become extra text nodes.

jQuery
var raw = "   <strong>Bold</strong>   ";
var withoutTrim = $.parseHTML(raw);
var withTrim = $.parseHTML(raw.trim());

console.log(withoutTrim.length);  // 3  (#text, STRONG, #text)
console.log(withTrim.length);     // 1  (STRONG only)
Try It Yourself

How It Works

  1. Raw string. Spaces before/after the tag are kept by the HTML parser.
  2. Without trim. Those spaces become #text nodes around STRONG.
  3. With trim. raw.trim() removes edge spaces first — one element remains.
  4. Practice. Prefer trim (or $.trim) when you only want element nodes.

Example 4 — keepScripts Default vs true

By default, script tags are stripped from the result array.

jQuery
var tag = "scr" + "ipt";
var snippet = "<p>Hi</p><" + tag + ">1</" + tag + ">";

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

console.log(safe.length);         // 1  (P only)
console.log(withScripts.length);  // 2  (P + SCRIPT)
Try It Yourself

How It Works

  1. Build safely. Split the word script so demos do not confuse HTML parsers.
  2. Default. $.parseHTML(snippet) drops the script — only P remains.
  3. keepScripts true. The script element is kept in the array (still use only trusted markup).
  4. Security. Leaving scripts out is safer, but attributes can still be dangerous after append — sanitize untrusted HTML.

Edge Cases & Pitfalls

Check these before parsing real templates or API HTML.

security

Not a sanitizer

Scripts may be stripped by default, but event-handler attributes and other vectors can still run after you insert nodes. Never treat parseHTML as XSS protection.

whitespace

Edge spaces become text nodes

Trim the string (or use $.trim) when you only want element nodes at the edges.

return type

Array, not a jQuery object

$.parseHTML returns a native array. Use $(nodes) if you need .find() or other collection methods.

XML

Use parseXML for XML

HTML fragments belong here. Well-formed XML feeds belong to $.parseXML().

Browser Support

jQuery.parseHTML() needs a browser DOM (native HTML parsing). It is available since jQuery 1.8+ in all modern browsers — it is not supported in Node.js, Bun, or Deno without a DOM polyfill.

✓ jQuery 1.8+ · Browsers only

jQuery.parseHTML()

Works in Chrome, Firefox, Safari, Edge, and other browsers with jQuery loaded. No Node.js support — use a DOM environment or a server HTML library there.

100% Browser support
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
$.parseHTML() Browsers

Bottom line: Use $.parseHTML(str) in the browser only. For Node.js, parse HTML with a server-side library instead of jQuery.

Performance Notes

ApproachCostBest for
$.parseHTML(str)O(n) in string sizeSmall/medium HTML fragments
Parse once, reuse nodesCheapestTemplates you mount more than once (clone if needed)
Re-parse the same stringWastefulAvoid in hot loops — cache the node array

Parsing dominates cost on large markup. Parse once, keep the node array (or a clone), and append without re-parsing the same string.

Key Takeaways

  • Role: $.parseHTML(str) → array of DOM nodes.
  • Scripts: off by default; set keepScripts only for trusted markup.
  • Trim: edge whitespace becomes #text nodes unless you trim first.
  • Security: sanitize untrusted HTML before append — parseHTML is not a filter.

One line: parse HTML into a node array with $.parseHTML, trim when needed, keep scripts off for untrusted input, then append only what you trust.

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. Append the array with .append() or inspect nodes first.
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). Even a string without tags becomes a text node in the returned array.
parseHTML returns a plain array of nodes and does not run scripts by default (keepScripts is false). $(html) builds a jQuery collection and inserting that HTML into the live document can still run malicious code. Use parseHTML when you want nodes first, then decide what to inject.
When keepScripts is false (the default), script elements in the HTML string are omitted from the returned nodes. When true, script tags are included in the array. Never pass untrusted HTML with keepScripts true.
Leading and trailing whitespace in the HTML string can become text nodes. The jQuery API recommends jQuery.trim() (or String.prototype.trim()) first when you want to avoid extra edge whitespace nodes.
When context is omitted, null, or undefined, jQuery 3.0+ uses a new detached document to parse HTML. That helps prevent inline event handlers from firing during parsing. Once you inject the nodes into the live page, handlers can still run — always sanitize untrusted input.
No. It is not a security filter. Indirect script execution (for example via event-handler attributes) is still possible. Clean or escape untrusted input from URLs, cookies, or forms before parsing and inserting.

Next: parseXML()

Learn how jQuery parses a well-formed XML string into an XMLDocument.

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.

9 people found this page helpful