Use $.parseHTML() when you have an HTML string and want DOM nodes without immediately inserting that string into the live page. Wrap the returned array with $(...), select the elements you need, then read text with .text() or attributes with .attr(). Parsing is not sanitizing: if the source is untrusted, clean or safely handle it before insertion.
This workflow separates three jobs: parsing a string, selecting nodes, and extracting values. Keeping them separate makes code easier to test and avoids treating HTML as trusted merely because jQuery accepted it.
The parsing-to-extraction workflow
- Parse explicitly. Call
$.parseHTML(htmlString); it returns an array of DOM nodes, as documented by jQuery. - Wrap the nodes. Pass the array to
$(nodes)to obtain a jQuery collection. - Select and traverse. Use selectors,
.find(),.first(),.eq(), or iteration. - Extract the right representation. Use
.text()for text,.attr(name)for an attribute, and.html()only when you actually need markup.
const htmlString = `
<article class="card" data-id="42">
<h2 class="title">Building a parser</h2>
<a class="read-more" href="/guides/jquery">Read guide</a>
</article>
`;
const nodes = $.parseHTML(htmlString);
const $fragment = $(nodes);
const title = $fragment.find(".title").first().text();
const link = $fragment.find("a.read-more").first().attr("href");
const id = $fragment.filter("article").add($fragment.find("article")).first().attr("data-id");
console.log({ title, link, id });
The resulting object contains the title text, link URL, and data-id value. Nothing in this example requires appending the fragment to document.body; extraction can happen entirely off-document.
Parsing an HTML fragment with $.parseHTML()
$.parseHTML() was added in jQuery 1.8. Its documented return value is an array of DOM nodes, not a jQuery object and not a sanitized representation. The input can contain one element, several sibling elements, text nodes, or a mixture.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
const nodes = $.parseHTML("<li>One</li><li>Two</li>");
const $items = $(nodes);
console.log($items.length); // 2
Context behavior in jQuery 3.0 and later
When the context argument is omitted or is null/undefined, jQuery 3.0 and later use a new document for parsing. Earlier versions used the current document. The change can improve isolation during parsing, but it does not make later insertion safe. The official documentation notes that internal jQuery calls may still pass the current document.
If your markup depends on a particular document, pass that document deliberately:
const nodes = $.parseHTML(htmlString, document, false);
The third argument controls whether scripts are kept. Leaving script elements out is generally preferable when you only need data; consult the API reference for the exact signature and version behavior.
Selecting parsed nodes
After wrapping the array, ordinary jQuery selectors and traversal methods apply. .find() searches descendants of the current collection. Methods such as .filter() inspect the current nodes themselves, which matters when the element you want is the root of the fragment.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteconst nodes = $.parseHTML(`
<div class="product" data-sku="A-17">
<span class="name">Keyboard</span>
<span class="price">$49</span>
</div>
`);
const $fragment = $(nodes);
// Root element:
const $product = $fragment.filter(".product").first();
// Descendants:
const name = $product.find(".name").text();
const priceText = $product.find(".price").text();
const sku = $product.attr("data-sku");
Use .first() or .eq(index) when a selector can match several nodes and your logic intentionally needs one. If you need every matching element, iterate instead of silently reading only one.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Extracting text with .text()
.text() returns the combined text of the matched elements and their descendants. It is the appropriate getter for headings, labels, paragraphs, and other human-readable content.
const $fragment = $($.parseHTML(`
<div>
<h2>First</h2>
<p>Second <strong>part</strong></p>
</div>
`));
const allText = $fragment.text();
const heading = $fragment.find("h2").text();
Whitespace and newline output can vary with browser parsing, so do not use raw .text() output as a formatting contract. Normalize only when your application requires it:
const normalized = $fragment.find("p").text().replace(/s+/g, " ").trim();
That normalization is an application choice; it can remove meaningful spacing in preformatted content, so apply it only to content where collapsed whitespace is acceptable.
Extracting attributes with .attr()
.attr(name) gets the named attribute from the first element in the matched set. It returns undefined when no matched element has that attribute.
const $links = $($.parseHTML(`
<a href="/one" data-id="1">One</a>
<a href="/two" data-id="2">Two</a>
`));
const firstHref = $links.attr("href"); // /one
For one value per element, map or loop over the collection:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
const records = $links.map(function () {
return {
text: $(this).text().trim(),
href: $(this).attr("href"),
id: $(this).attr("data-id")
};
}).get();
console.log(records);
Use the exact attribute name you need: href, src, alt, data-id, aria-label, or another attribute present in the markup. Do not assume a missing attribute is an empty string; handle undefined explicitly when absence matters.
Text, markup, and attributes: choose deliberately
| Need | Use | Result and scope |
|---|---|---|
| Readable content from matches and descendants | .text() |
Combined text; whitespace/newlines may differ by parser |
| One named attribute | .attr("name") |
Attribute from the first matched element |
| Each match’s value | .each() or .map() with .attr() |
One record per element |
| Inner markup of one match | .html() |
HTML string from the first matched element |
.html() is not a text extractor. It returns markup, and using that markup in an insertion path can expose the same security issues as inserting the original string.
Security: parsing does not sanitize
Do not pass untrusted HTML directly to jQuery constructors, $.parseHTML() followed by insertion, or methods such as .html(). The parseHTML documentation warns that parse-time behavior does not guarantee safety after injection; event-handler attributes and indirect execution paths, such as an <img onerror>, remain relevant. The jQuery constructor documentation likewise describes risks when HTML strings are interpreted.
Safer handling pattern
- Classify the source. Treat user submissions, remote responses, stored CMS content, and URL-derived strings as untrusted unless your application has established otherwise.
- Extract data without injecting nodes when possible. You can parse, select, and read values entirely off-document.
- If display requires insertion, sanitize or escape for the exact output context using a maintained sanitizer or your platform’s appropriate escaping mechanism. The cited jQuery references establish the risk but do not endorse one sanitizer.
- Do not copy extracted
.html()into a live container merely because it came from parsed nodes.
// Data extraction without insertion:
const nodes = $.parseHTML(untrustedString);
const title = $(nodes).find("title").first().text();
// Avoid this with untrustedString or untrusted markup:
// $("#output").html(untrustedString);
Complete reusable extraction function
function parseCards(htmlString) {
const nodes = $.parseHTML(htmlString);
const $root = $(nodes);
return $root.filter(".card").add($root.find(".card")).map(function () {
const $card = $(this);
return {
id: $card.attr("data-id"),
title: $card.find(".title").first().text().trim(),
href: $card.find("a").first().attr("href")
};
}).get();
}
The filter().add() combination handles cards that are either root nodes or descendants. In a controlled template, you can simplify it to $root.find('.card'); choose the form that matches the actual fragment shape.
Troubleshooting common failures
“My selector finds nothing”
Check whether the desired element is a root node. .find() searches descendants, not the current collection itself. Use .filter() for roots, or combine both when fragments vary.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
“I only receive one attribute”
That is the documented getter behavior: .attr() reads the first match. Iterate with .each() or .map() for a list.
“The text contains unexpected spaces or line breaks”
Browser parsers can produce different whitespace and newline results. Select the narrowest element and normalize whitespace only where your data model permits it.
“The HTML appeared to execute”
Parsing is not sanitization, and injecting parsed content can activate event attributes or scripts. Remove the injection path, treat the source as untrusted, and sanitize or escape it for the intended context.
“The result is an array, not a jQuery object”
That is expected. Wrap it: const $fragment = $($.parseHTML(htmlString));.
“A selector works on the page but not in my fragment”
Do not rely on page-level ancestors, IDs, or elements that are not present in the string. Inspect the fragment’s actual roots and query from the wrapped collection.
Free tools Windows power users keep installed
One-click scans. No signup required.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Performance, reliability, and version considerations
This API composition has no documented performance guarantee in the cited references, so avoid promising a fixed speed or capacity. For reliability, validate required fields, handle missing attributes, and keep selectors aligned with the markup contract. Pin or document your jQuery version when behavior around parsing context matters, especially across the jQuery 3.0 change.
For very large documents, narrow the input before parsing when your data source allows it, and extract only the fields you need. This is an engineering choice rather than a claim about a benchmark.
Or skip the browser setup
If your real goal is obtaining a clean screenshot of a page rather than parsing an HTML string, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF. It accepts cookie or consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status.
It also supports full-page captures with lazy images, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF paper settings and page ranges, HTML/CSS-to-image, custom JavaScript and CSS, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for request options. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up free to try it.
Other runnable clients
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', data);
Frequently Asked Questions
Does $.parseHTML() return a jQuery object?
No. It returns an array of DOM nodes; wrap that array with $(nodes) before using jQuery traversal and getters.
Can I extract data without adding parsed HTML to the page?
Yes. Parse, wrap, select, and read values in memory. Only insert nodes when the application actually needs to render them.
Which method should I use for an element’s inner HTML?
Use .html(), but remember that it returns markup from the first match and must be handled as untrusted content when its source is not trusted.
The Bottom Line
For a controlled HTML string, the dependable pattern is $( $.parseHTML(string) ), followed by precise selectors and the appropriate getter: .text() for text, .attr() for attributes, and .html() only for markup. Keep extraction separate from insertion, and never treat parsing as sanitization.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

