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:
JavaScript
x
8
1
<div class="parent">
2
<div>
3
<p>Child 1</p>
4
<p>Child 2</p>
5
<p>Child 3</p>
6
</div>
7
</div>
8
The code I try to do:
JavaScript
1
22
22
1
import cheerio from 'cheerio';
2
3
const html = `
4
<div class="parent">
5
<p>Child 1</p>
6
<p>Child 2</p>
7
<p>Child 3</p>
8
</div>
9
`;
10
11
const $ = cheerio.load(html);
12
13
$('.parent').children().wrap('<div></div>');
14
15
console.log($.html());
16
// Output:
17
// <div class="parent">
18
// <div><p>Child 1</p></div>
19
// <div><p>Child 2</p></div>
20
// <div><p>Child 3</p></div>
21
// </div>
22
Advertisement
Answer
Use method wrapInner
like that:
JavaScript
1
2
1
$('.parent').wrapInner("<div></div>");
2