Skip to content
Advertisement

How to wrap the children/child of element with one tag using cheerio?

I have p tags inside div element.

I want to wrap the div children/child with div tag using cheerio library.

I try to use wrap: $('.parent').children().wrap('<div></div>'); But it wraps every element in my div.

Is it possible to wrap all the children with one tag div like this:

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

The code I try to do:

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>

Advertisement

Answer

Use method wrapInner like that:

$('.parent').wrapInner("<div></div>");
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement