Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchLoad the HTML with Cheerio, select the element you want to start from, then use siblings(), next(), prev(), nextAll(), prevAll(), nextUntil() or prevUntil() to traverse its sibling elements. Use siblings() for elements on either side, directional methods for one side, and an Until method when a matching element marks the stopping point. These methods return a new selection; they do not change the starting selection. Cheerio’s traversal guide documents the methods and its introduction documents installation and Node.js usage.
Install Cheerio and load the HTML
Install the package in your project with npm install cheerio. The official introduction currently states a requirement of Node.js 22.19 or later; check that page when setting up a new project because runtime requirements can change. It documents both ES module and CommonJS usage. Cheerio introduction
Here is a complete ES module example. Save it as sibling-demo.mjs and run it with node sibling-demo.mjs:
import * as cheerio from 'cheerio';
const html = `
<ul>
<li class="first">One</li>
<li class="target">Two</li>
<li class="last">Three</li>
</ul>
`;
const $ = cheerio.load(html);
const target = $('li.target');
console.log(target.siblings().map((_, el) => $(el).text()).get());
// [ 'One', 'Three' ]
console.log(target.next().text());
// Three
console.log(target.prev().text());
// One
console.log(target.nextAll().map((_, el) => $(el).text()).get());
// [ 'Three' ]
The key operation is const target = $('li.target'): first identify the element, then traverse relative to that selection. In CommonJS projects, the documented import form is const cheerio = require('cheerio');; the traversal calls work on the resulting $ selections in the same way. Cheerio introduction
#1 Best Overall
- HTML CSS Design and Build Web Sites
- Comes with secure packaging
- It can be a gift option
Choose the sibling method that matches your goal
A sibling shares the same parent as the starting element. Cheerio’s traversal methods operate on sibling elements, not on nested descendants. Pick the direction and stopping behavior you need:
| Goal | Method | What it selects |
|---|---|---|
| Other siblings on either side | siblings() |
All sibling elements except the starting element |
| Immediately following element | next() |
At most the next sibling element |
| Immediately preceding element | prev() |
At most the previous sibling element |
| All following elements | nextAll() |
Every following sibling element |
| All preceding elements | prevAll() |
Every preceding sibling element |
| Following elements up to a boundary | nextUntil(selector) |
Following siblings before, but not including, the boundary match |
| Preceding elements up to a boundary | prevUntil(selector) |
Preceding siblings before, but not including, the boundary match |
The API reference documents optional selector filters for these methods. For example, $('.apple').nextAll('.orange') selects following siblings matching .orange. Filtering can be useful when the intervening siblings are irrelevant. Cheerio API reference
Get every sibling except the target
Use siblings() when you need the other children of the same parent regardless of which side they are on. In the list example, target.siblings() selects both “One” and “Three”; it does not include “Two,” the starting element. Convert a selection to ordinary values with map() and get() when you need an array of text strings rather than another Cheerio selection:
const labels = target.siblings().map((_, el) => $(el).text()).get();
console.log(labels); // [ 'One', 'Three' ]
Get only the adjacent sibling
Use next() or prev() when adjacency matters. Each selects no more than one element in that direction. If the target is the last item in its parent, next() has no next element to select; if it is first, prev() has none. Do not use these methods when you mean “find the next matching element somewhere later”—that is a directional search, for which nextAll(selector) may be appropriate.
Rank #2
Get all siblings in one direction
nextAll() and prevAll() traverse the full run of sibling elements forward or backward, respectively. An optional selector can narrow the result. For example:
const laterWarnings = $('li.target').nextAll('.warning');
const earlierHeadings = $('li.target').prevAll('h3');
These searches remain within the target’s sibling relationship. They do not search inside a sibling’s nested content.
Stop at a boundary element
Use nextUntil(selector) or prevUntil(selector) when the relevant siblings form a run that ends at a known boundary. The matching boundary is excluded from the returned selection. For instance, to collect items after a starting item only until the next element marked as a section break:
const sectionItems = $('li.target').nextUntil('.section-break');
If there is no matching boundary sibling, there is no matching boundary at which to stop, so inspect the returned selection against the structure you expect. Add an ordinary selector filter if you also need to restrict which elements in the run are kept. Traversal method behavior
Rank #3
Use a CSS sibling combinator when it is simpler
If you can express the relationship as a selector from the outset, a CSS sibling combinator can avoid a separate traversal call:
const immediatelyFollowingParagraph = $('h2 + p');
const followingParagraphs = $('h2 ~ p');
The adjacent sibling combinator + matches a p immediately following an h2. The general sibling combinator ~ matches following p elements under the same parent. These are directional: they do not select preceding siblings or all siblings on both sides. Cheerio selector guide
Keep sibling selectors distinct from descendant selectors. div p can match paragraphs nested anywhere inside a div, while div > p restricts the paragraph to a direct child. Neither means “a paragraph that is a sibling of this selected paragraph.” Use + or ~ for that relationship.
Find siblings in a real HTML fragment
For example, suppose a page fragment contains product rows and you want the later rows with a particular class after a selected row. Load the fragment, select the starting row, and traverse within its parent:
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #4
- Brand: Wiley
- Set of 2 Volumes
- A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
import * as cheerio from 'cheerio';
const html = `
<div class="products">
<article class="product" data-id="a">Alpha</article>
<article class="product selected" data-id="b">Beta</article>
<article class="product featured" data-id="c">Gamma</article>
<article class="product" data-id="d">Delta</article>
</div>
`;
const $ = cheerio.load(html);
const selected = $('.product.selected');
const laterProducts = selected.nextAll('.product');
const results = laterProducts.map((_, el) => ({
id: $(el).attr('data-id'),
name: $(el).text().trim(),
})).get();
console.log(results);
// [ { id: 'c', name: 'Gamma' }, { id: 'd', name: 'Delta' } ]
The selector filter matters here because the intent is to collect later product elements only. For a more tightly bounded group, change the traversal to selected.nextUntil('.group-end', '.product'); the boundary element itself is not included. Before relying on the result, check that the initial selector found the element you expect and that the markup has the parent-child arrangement the traversal assumes.
Handle empty selections and structural mismatches
A selector or traversal can produce an empty selection. Chaining more methods onto an empty selection does not make a missing target appear, and reading its text will not tell you whether the selector matched the intended source element. Check the starting selection before deriving output:
const target = $('li.target');
if (target.length === 0) {
throw new Error('Could not find the target list item');
}
const next = target.next();
if (next.length === 0) {
console.log('The target has no following sibling element');
} else {
console.log(next.text().trim());
}
If a traversal returns too many or too few results, inspect the parsed markup and verify the parent. A node nested in another element is not a sibling of that element’s children. Use find() to search descendants or children() for direct children when those are the actual relationships you mean; sibling traversal is not a substitute for either.
Know when Cheerio cannot see the target
Cheerio parses the markup supplied to it; it does not execute the page’s JavaScript or render a browser view. If a framework creates the target element only after client-side code runs, that element will not be present in the original markup Cheerio parses. The Cheerio introduction describes it as a library for parsing and manipulating markup rather than a browser. Cheerio introduction
Recommended Free Tools
Best Value
In that case, obtain markup that includes the element or use browser automation or a DOM-emulation approach when client-side rendering is essential. A screenshot can help you inspect what a visitor sees, but an image is not an HTML tree and cannot be passed to Cheerio as sibling nodes.
Or skip the browser setup
If your goal is to capture a page visually rather than query its HTML structure, ScreenshotNeo provides a screenshot API and MCP server. It does not replace Cheerio for finding sibling elements or return DOM nodes; use it when the needed output is a screenshot or PDF. One Node.js request looks like this:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
See the ScreenshotNeo API documentation for request options. Cookie banners, popups and chat widgets are removed before the shot; bot checks, blank pages and failed loads are never billed; an MCP server lets AI agents take screenshots; and 1,000 screenshots a month are free with no card, with paid plans starting at $5 for 3,000. Sign up for free ScreenshotNeo access.
Troubleshoot common sibling-selection problems
- The result is empty: First check whether the starting selector matched anything. Then confirm the target has a sibling in the requested direction and that both elements share a parent.
- The adjacent element is not the one expected:
next()selects the immediately following sibling element, not the next sibling matching an arbitrary condition later in the parent. UsenextAll(selector)when you need a later matching sibling. - Nested content appears to be missing: Sibling traversal does not descend into children. Use
find()for descendants orchildren()for direct children. - The boundary is included in your output:
nextUntil()andprevUntil()stop before the matched boundary; they do not include it. Select the boundary separately if the task needs it. - The element appears in a browser but not in Cheerio: Check whether it exists in the markup being parsed. Cheerio does not execute page JavaScript, so browser-created content may require a rendering or automation step.
- Several elements match the starting selector: Tighten the selector so it identifies the intended target, or deliberately process each match. An ambiguous starting selection can make the resulting traversal different from the one you intended.
Frequently Asked Questions
Do Cheerio sibling methods change the original selection?
No. The traversal guide says each method returns a new selection and leaves the original selection untouched. You can keep using the starting selection after deriving a sibling selection.
Can I use Cheerio to retrieve a rendered page’s screenshot?
No. Cheerio parses markup; it does not render a browser view. Use a browser-based capture tool if you need an image or PDF, and use Cheerio when you need to traverse HTML elements.
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.

