October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
browser APIs

How to Capture Part of a Webpage With jQuery (HTML, Text, Forms, Selection, or Screenshots)

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The right jQuery method depends on what “capture” means. Use $("#target").html() for an element’s current inner HTML, $("#target").text() for readable descendant text, and $("#form").serialize() for URL-encoded form controls. None of these creates an image. For the pixels users see, use the browser’s screen-capture APIs or a screenshot service.

Choose the output before choosing the API

“Capture part of a webpage” can describe several different outputs. The target may be a CSS-selected element, the text a user highlighted, named form fields, or a rendered rectangle. These are different representations with different browser and security behavior.

What you need Use What you receive User permission
Markup inside one element .html() Current DOM inner HTML of the first match No
Readable content .text() Combined descendant text No
Form submission data .serialize() URL-encoded successful controls No
User-highlighted text Selection and Range APIs Selected string or document range No
Rendered pixels Screen/display capture Image frames from a captured stream Usually yes

Keep the distinction explicit in your code. Reading the DOM does not preserve the original network response bytes, CSS rendering, fonts, or a screenshot.

Get an element’s HTML with jQuery

Read the inner markup

The getter returns the contents of the first element matched by the selector; it does not include that element’s own opening and closing tags.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
const html = $("#article-section").html();
console.log(html);

For example, given <section id="article-section"><h2>News</h2><p>...</p></section>, the result starts with <h2>, not <section>. jQuery uses the browser’s innerHTML property, so parsing and serialization can normalize quotes, optional tags, whitespace, and attribute order. It is a representation of the live DOM, not a byte-for-byte copy of the server’s source.

Make multiple matches deterministic

A selector can match many nodes, but the getter reads only the first. Select the intended node, or choose it deliberately:

const firstCard = $(".card").first().html();
const thirdCard = $(".card").eq(2).html();
const allCards = $(".card").map(function () {
  return $(this).html();
}).get();

If no element matches, the getter returns undefined. Check that case before writing the value to a file, sending it to an API, or inserting it elsewhere.

Include the wrapper when needed

Use .prop("outerHTML") when the selected element itself must be included:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const completeNode = $("#article-section").prop("outerHTML");

This still captures the current DOM node only. It does not include the document head, external stylesheets, or other page resources.

Get text from an element

Read descendant text

const text = $("#article-section").text();
console.log(text);

.text() combines text from the matched element and its descendants. It is appropriate when you need content rather than tags. Newlines and whitespace can vary with browser parsing and the page’s DOM structure, so normalize only when your output format requires it:

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
const cleanText = $("#article-section")
  .text()
  .replace(/s+/g, " ")
  .trim();

For an input or textarea, use .val(); the control’s value is not its child text node:

const email = $("#email").val();
const message = $("#message").val();

Capture several elements

Unlike .html(), .text() combines the text of all matched elements:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const headings = $("article h2").text();

If you need a separate value for each match, iterate instead of relying on one combined string:

const headingTexts = $("article h2").map(function () {
  return $(this).text().trim();
}).get();

Capture form values as a query string

When “capture” means collecting fields for submission or storage, .serialize() creates standard URL-encoded text from successful form controls.

const queryString = $("#contact-form").serialize();
console.log(queryString);

A control generally needs a name attribute. Unchecked checkboxes and radio buttons are omitted, as are disabled controls. File inputs are not included; upload files with FormData instead. Selecting a form and its child controls together can duplicate values, so select the form alone:

// Correct: controls are included once
const data = $("#contact-form").serialize();

// Avoid selecting both the form and all of its children
const duplicateProne = $("#contact-form, #contact-form :input").serialize();

Inspect the resulting string before appending it to a URL. It is encoded for transport, not a structured JavaScript object. Parse it with URLSearchParams when you need individual fields.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Capture text the user highlighted

A CSS selector cannot identify an arbitrary portion of a text node. For the user’s current highlight, use the browser’s Selection API:

const selection = window.getSelection();
const selectedText = selection ? selection.toString() : "";
console.log(selectedText);

An empty string means there is no active text selection (or the selection is collapsed). For richer operations, inspect the range when one exists:

const selection = window.getSelection();
if (selection && selection.rangeCount > 0 && !selection.isCollapsed) {
  const range = selection.getRangeAt(0);
  console.log(range.startContainer, range.endContainer);
  console.log(range.cloneContents());
}

A range can contain whole nodes or only part of a text node. Selection and focus are separate concerns: changing a selection programmatically does not guarantee that keyboard focus moves with it, so manage focus explicitly in interactive interfaces.

Take a screenshot of one element

If the requirement is an image of what the visitor sees, do not use .html() or .text(). Browser display capture asks the user to choose a source, then returns a media stream. Element Capture can restrict the stream to a rendered DOM tree and its descendants. Region Capture crops to an element’s bounding box and can include overlapping content within that rectangle. Support differs by browser and changes over time; verify compatibility for the browsers you target.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Minimal display-capture flow

The following example illustrates the permission-dependent flow. It finds the target, requests a display stream, grabs a frame, and encodes it as PNG:

async function captureElementImage() {
  const target = document.querySelector("#article-section");
  if (!target) throw new Error("Target element was not found");

  const stream = await navigator.mediaDevices.getDisplayMedia({
    video: true,
    audio: false
  });

  try {
    // Element/Region Capture APIs are browser-dependent; feature-detect them
    // and apply the appropriate restriction for your target browser.
    const track = stream.getVideoTracks()[0];
    const imageCapture = new ImageCapture(track);
    const bitmap = await imageCapture.grabFrame();

    const canvas = document.createElement("canvas");
    canvas.width = bitmap.width;
    canvas.height = bitmap.height;
    canvas.getContext("2d").drawImage(bitmap, 0, 0);

    const blob = await new Promise(resolve =>
      canvas.toBlob(resolve, "image/png")
    );
    return blob;
  } finally {
    stream.getTracks().forEach(track => track.stop());
  }
}

This is not a silent page scraper. The browser may show a chooser, deny the request outside a secure context, or expose only the surface the user selected. A production implementation should feature-detect the capture and restriction APIs, handle cancellation, and tell the user exactly what will be shared.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Security: reading HTML is not the same as safely displaying it

Reading a string with .html() is different from inserting that string into another document. HTML-accepting methods can execute script tags or executable attributes. Do not insert strings obtained from URL parameters, cookies, or form inputs without removing or escaping untrusted content. If the goal is to display captured data as text, use .text() or the DOM’s text-content APIs so the string is not interpreted as markup.

// Safe for displaying an untrusted string as text
$("#preview").text(untrustedValue);

// Do not do this with untrustedValue
$("#preview").html(untrustedValue);

Even trusted page content may contain user-generated markup. Treat every later insertion as a security boundary and sanitize with a well-maintained sanitizer when HTML must be preserved.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common failures and fixes

“My HTML is missing the outer element”

.html() intentionally returns inner HTML. Use .prop("outerHTML") when the wrapper is part of the required output.

“The result is undefined”

The selector matched nothing, often because the script ran before the DOM existed or because an ID/class is wrong. Run after DOM ready and verify the selector:

$(function () {
  const target = $("#article-section");
  if (!target.length) return console.error("Target not found");
  console.log(target.html());
});

“Text or whitespace looks different”

DOM serialization and browser parsing can normalize whitespace and line breaks. Define an explicit normalization rule, and do not treat the result as original source bytes.

“The form value is absent”

Check the control’s name, checked state, and disabled state. Remember that file inputs are excluded from .serialize().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

“The screenshot prompt was blocked or cancelled”

Display capture requires user permission and normally a secure context. Handle NotAllowedError, cancellation, unsupported APIs, and a stopped track. Offer a DOM/text fallback when an image is not essential.

“The screenshot contains more than the element”

Display capture starts from the surface the user selected. Element and region restriction semantics differ, and region cropping may include overlapping content. Test the exact browser versions and layout states you support.

Or skip the browser setup

For a server-side image of a URL or a selected CSS element, ScreenshotNeo provides a single request instead of a permission-driven display stream. It can accept consent banners before capture and remove more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and whether it was billed. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.

The API supports full-page or CSS-selector element capture, lazy-image loading, dark mode, device presets or custom viewports, retina scale, PDF paper and page controls, custom CSS and JavaScript, clicks, selector waits, delays, network-idle waits, request/resource blocking, headers, cookies, user agents, Authorization, timezone, geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous signed webhooks, bulk capture of up to 100 URLs per call, usage reporting and an OpenAPI specification. Parameter names used by other screenshot APIs also work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

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 bytes = Buffer.from(await res.arrayBuffer());
require('node:fs').writeFileSync('shot.webp', bytes);

See the complete parameter reference in the ScreenshotNeo documentation. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account to try it.

Practical decision checklist

  • Need current markup inside one node: .html().
  • Need the node plus its wrapper: .prop("outerHTML").
  • Need readable content: .text(); use .val() for fields.
  • Need form submission encoding: .serialize(), with named successful controls.
  • Need the user’s highlight: Selection and Range APIs.
  • Need pixels: permission-based display capture, with browser feature detection, or ScreenshotNeo for a server-side shot.
  • Any captured string that will be inserted later: treat it as untrusted until sanitized or rendered as text.

Frequently Asked Questions

Does jQuery have a built-in screenshot method?

No. jQuery reads and manipulates the DOM; rendered-pixel capture uses browser display-capture APIs or a separate screenshot service.

How can I capture only the second matching element?

Use an explicit selector or index such as $(“.card”).eq(1).html(), remembering that indexes are zero-based.

Can .serialize() upload a selected file?

No. File inputs are excluded; use FormData and an upload request for file data.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can .html() recover the exact HTML downloaded from the server?

No. It reads the live DOM through innerHTML, whose parsing and serialization may differ from the original response bytes.

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.

Leave a Reply

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

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.