You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Cheerio将元素的所有子元素用单个标签包裹?

问题

我有一个包含<p>标签的<div>元素,希望用Cheerio库把该<div>的所有子元素用单个<div>标签包裹。尝试用wrap方法:$('.parent').children().wrap('<div></div>');,但这个方法会给每个子元素单独套一个div,达不到预期效果。

预期效果:

<div class="parent">
 <div>
    <p>Child 1</p>
    <p>Child 2</p>
    <p>Child 3</p>
 </div>
</div>

我尝试的代码及输出:

import cheerio from 'cheerio';

const html = `
  <div class="parent">
    <p>Child 1</p>
    <p>Child 2</p>
    <p>Child 3</p>
  </div>
`;

const $ = cheerio.load(html);

$('.parent').children().wrap('<div></div>');

console.log($.html());
// Output:
//   <div class="parent">
//     <div><p>Child 1</p></div>
//     <div><p>Child 2</p></div>
//     <div><p>Child 3</p></div>
//   </div>
解决方案

用Cheerio的wrapAll()方法就能实现——它会把所有匹配到的元素包裹在同一个容器标签里,而不是给每个元素单独包裹。

修改后的代码:

import cheerio from 'cheerio';

const html = `
  <div class="parent">
    <p>Child 1</p>
    <p>Child 2</p>
    <p>Child 3</p>
  </div>
`;

const $ = cheerio.load(html);

// 用wrapAll替代wrap
$('.parent').children().wrapAll('<div></div>');

console.log($.html());
// Output:
//   <div class="parent">
//     <div>
//       <p>Child 1</p>
//       <p>Child 2</p>
//       <p>Child 3</p>
//     </div>
//   </div>

内容的提问来源于stack exchange,提问作者Jon Sud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:55:21