#5562·cheerio

wrap and wrapAll ignore removed elements

Author: StrohuttCreated Sep 27, 2026Updated Sep 27, 2026

After removing an element, .wrap() and .wrapAll() silently leave it unwrapped:

javascript
const $ = cheerio.load('<main><span>hello</span></main>');
const item = $('span').remove();
item.wrap('<section class="wrapper"></section>');
console.log(item.parent().prop('outerHTML'));
// undefined

The same happens with wrapAll. In jQuery 4.0.0, both produce <section class="wrapper"><span>hello</span></section>; the original <main> stays empty.

Reproduced against Cheerio main at 0ab9a8e943bb86704ceb962770bc46647404ea45 on Node 26.10.0. .wrap() returns before moving a node when it has no parent, while .wrapAll() loses the wrapper selection through insertBefore on a detached target.

I can add a focused fix for both methods, with regression coverage for removed nodes and the existing document-root behavior.