DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober 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 Now×
Skip to content
browser APIs

How to Screenshot a Single Element with dom-to-image

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

To render one element with dom-to-image, first select its DOM node, then pass that node—not a selector string—to domtoimage.toPng(node). The call returns a promise that resolves to a PNG data URL. You can display it, download it, or pass it to other browser code.

Capture a single element as a PNG

Install and load dom-to-image in your browser application using the package setup appropriate to your project. Then select the element and call toPng. This example uses an ES module import and appends the result as an image:

import domtoimage from 'dom-to-image';

const node = document.getElementById('my-element');

if (!node) {
  throw new Error('Element not found');
}

domtoimage.toPng(node)
  .then((dataUrl) => {
    const image = new Image();
    image.src = dataUrl;
    document.body.appendChild(image);
  })
  .catch((error) => {
    console.error('Could not render element', error);
  });

Replace my-element with the target element’s actual ID. The null check is ordinary defensive DOM code, not a library requirement: it prevents a missing element from being passed into the renderer. The promise is asynchronous, so use the result inside .then() or with await.

Use a selector when the element has no ID

Resolve a CSS selector to a DOM node before calling the library. For example:

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.
#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 node = document.querySelector('.invoice-card');

if (!node) {
  throw new Error('No element matched .invoice-card');
}

const dataUrl = await domtoimage.toPng(node);

querySelector returns the first matching node or null. The capture API takes the node itself; passing '.invoice-card' as a string is not the documented node-to-image pattern.

Display, download, or pass along the result

toPng resolves to a data URL, which can be assigned to an image source or used as a download link. To prompt a browser download, create a temporary anchor:

const node = document.querySelector('.invoice-card');
if (!node) throw new Error('Element not found');

try {
  const dataUrl = await domtoimage.toPng(node);
  const link = document.createElement('a');
  link.download = 'invoice-card.png';
  link.href = dataUrl;
  link.click();
} catch (error) {
  console.error('Could not render element', error);
}

For larger downstream workflows, choose an output suited to the next step rather than converting formats unnecessarily. The original project documents these output methods:

Method Result Useful when
toPng(node) PNG data URL You need a lossless raster image or an image source.
toJpeg(node, options) JPEG data URL You want a compressed raster image and can choose a quality value.
toSvg(node) SVG data URL You want the serialized SVG representation rather than a raster result.
toBlob(node) Blob Browser code downstream expects a Blob.
toCanvas(node) Canvas You need to continue drawing or processing in canvas code.
toPixelData(node) Pixel data You need raw pixel values for image processing.

These functions accept a DOM node and rendering options and return promises. The documentation does not establish a current quality or speed ranking among these formats; select by the format your application needs.

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.
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

Configure what appears in the image

The documented rendering options let you control the captured subtree’s appearance and resource handling. Options are passed as the second argument:

const dataUrl = await domtoimage.toPng(node, {
  bgcolor: '#ffffff',
  width: 800,
  height: 600,
  style: {
    transform: 'scale(1)',
  },
  filter: (child) => child.tagName !== 'BUTTON',
});

Exclude descendants with filter

filter(node) should return true to retain a descendant and false to exclude it. Excluding a node also excludes its descendants. The filter is not called for the root element passed to the capture method, so it cannot remove that root; select a different root if you need to omit it. For example, the filter above removes button descendants from the captured card.

Set background, dimensions, and style

  • bgcolor sets the background color for the rendered output.
  • width and height set the rendered node dimensions.
  • style applies style overrides to the node during rendering.

Use these when the default rendered dimensions or appearance do not match the output you need. Treat dimension changes as rendering settings; they do not change the fact that the input is a DOM node.

Choose JPEG quality and control resource fallbacks

  • quality sets JPEG quality from 0 to 1; it is relevant to toJpeg.
  • cacheBust appends the current time to resource URLs.
  • imagePlaceholder supplies a data URL to use when an image fetch fails. Without a placeholder, an image failure throws.

A placeholder can help an application deliberately tolerate unavailable images, but it also means the output may contain the fallback instead of the intended asset. If the image is important, fix its loading or access problem rather than masking it.

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.

What dom-to-image actually captures

This is not an operating-system screenshot or a browser-native screenshot of the visible viewport. The original project describes a rendering process that recursively clones the selected node, copies computed styles, recreates pseudo-elements, embeds web fonts and images, serializes the clone to XML, and wraps it in SVG foreignObject. For PNG and pixel output, that SVG is loaded as an image and rendered through an off-screen canvas.

That implementation explains both the appeal and the constraints: it can render a chosen DOM subtree, but success and fidelity depend on resource fetching, SVG foreignObject behavior, canvas security, and browser behavior. Content that is visible in the page is not automatically guaranteed to be available to the renderer.

Prepare the page and handle common failures

Capture after the target has its final layout and the resources it needs have loaded. This is practical guidance for a workflow that clones DOM and fetches styles, images, and fonts; it is not a promise of pixel-identical output in every browser or page.

Element not found

If selection returns null, the selector does not match at capture time. Check the ID or selector spelling, ensure the target has been inserted into the DOM, and run the capture after the relevant rendering step. Keep the null check so this failure is reported before the library call.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

Remote images, backgrounds, or fonts are missing

External resource access can affect completeness. Verify that the browser can fetch the image, background image, or font in the page context and that the resource is ready before capture. If an image fetch fails, imagePlaceholder can provide a fallback data URL; otherwise the documented behavior is for the image failure to throw.

Canvas is tainted or output fails around cross-origin content

The original README warns that a captured canvas can fail when tainted by cross-origin content. Remote images and other assets are therefore not merely a loading concern: browser security can prevent their pixels from being used in canvas output. Check the relevant resource access permissions and test the exact asset and browser combination you intend to support.

Styles differ from the page

The renderer copies computed styles into a clone and recreates pseudo-elements, but a clone-and-serialize path is not equivalent to capturing the browser’s final screen. Confirm that relevant stylesheets and fonts have loaded before invoking the method. The original README also notes a Firefox issue involving some external stylesheets, so investigate stylesheet loading when output differs in that browser.

Browser compatibility is uncertain

The original README’s support notes are historical: it reports tests with Chrome 49 and Firefox 45 at the time, and says Internet Explorer was unsupported because it lacked SVG foreignObject; Safari was marked unsupported because of stricter security around foreignObject. Those old test-version statements are not current compatibility verification. Test the browsers and content your own application supports rather than treating those version numbers as a modern support matrix.

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.

Server-side rendering, iframes, video, and size limits

The separate dom-to-image-more fork documents additional caveats: it requires a browser DOM rather than server-only rendering, browsers impose canvas dimension limits, cross-origin iframe content cannot be accessed, and video needs a poster or a caller-created image/canvas representation. These are fork-specific documented caveats; do not assume they are a complete or guaranteed statement of the original package’s behavior. In either case, DOM rendering belongs in a browser context with access to the content to be rendered.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture a page or a CSS-selected element from a URL without wiring a DOM-rendering library into the page, ScreenshotNeo offers a screenshot API. Its element-capture option targets a CSS selector. A single request can return an image or PDF; see the ScreenshotNeo API documentation for request options.

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

ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before the shot; those cleanup steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, with response headers reporting the page verdict and billing status. An MCP server provides screenshot tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000 screenshots.

Create a free ScreenshotNeo account to start with 1,000 screenshots a month and no card.

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

When this approach is the right fit

Use dom-to-image when the target is already a DOM element in your browser application and you want to create an image representation there. It is especially useful when the application needs a DOM subtree rendered to a data URL, Blob, canvas, SVG, or pixel data. If instead you need a screenshot of a URL without running capture code within that page, use a browser-level or hosted capture workflow; the approaches solve different problems.

Frequently Asked Questions

Does dom-to-image capture the whole browser window?

No. It renders the DOM node you pass to it and its included descendants; it is not an operating-system or viewport screenshot.

Can I use a CSS selector directly in toPng()?

No. Resolve the selector first with a DOM method such as document.querySelector, then pass the resulting node.

Does the filter option remove the root element?

No. The filter is not called on the root capture node. It filters descendants, and excluding a descendant also excludes its subtree.

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

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 *

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

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

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.