Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete just the parent Element in DOM using cheerios

Following is the file structure

<ABCList>
<ABC>
    <RL>3166</RL>
    <Client>42@gmail.com</Client>
<TravelerList>
        <Traveler>
            <FirstName>abc</FirstName>
            <LastName>zyz</LastName>
            <EmailAddress>xyz@gmail.com</EmailAddress>
            <PhoneNumber>5145845</PhoneNumber>
        </Traveler>
    </TravelerList>
</ABC>
</ABCList>

I want to to remove just from the file structure and keep the rest as it is. Following is what i have tried and it is removing just to parent element but it removes parent and child.

$("ABCList").remove()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you’re looking for unwrap:

const cheerio = require("cheerio"); // ^1.0.0-rc.12

const html = `<ABCList>
<ABC>
    <RL>3166</RL>
    <Client>42@gmail.com</Client>
<TravelerList>
        <Traveler>
            <FirstName>abc</FirstName>
            <LastName>zyz</LastName>
            <EmailAddress>xyz@gmail.com</EmailAddress>
            <PhoneNumber>5145845</PhoneNumber>
        </Traveler>
    </TravelerList>
</ABC>
</ABCList>`;

const $ = cheerio.load(html, {xml: true});
$("ABCList ABC").unwrap();
console.log($.html());

Output:

<ABC>
    <RL>3166</RL>
    <Client>42@gmail.com</Client>
<TravelerList>
        <Traveler>
            <FirstName>abc</FirstName>
            <LastName>zyz</LastName>
            <EmailAddress>xyz@gmail.com</EmailAddress>
            <PhoneNumber>5145845</PhoneNumber>
        </Traveler>
    </TravelerList>
</ABC>

This is in my Cheerio Cheatsheet: "Lift children up to a parent".

It’s less optimal, but $("ABCList").replaceWith($("ABCList").html()); is also possible.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading