Search code examples
cheerio

using cheeriojs to output a specific tag as-is


I am using cheeriojs to parse some xml

const $ = cheerio.load(xml, {
    normalizeWhitespace: true,
    xmlMode: true
})

This is probably something very basic that eludes me, but I can't figure out how to output the selected element verbatim. For example, I have

<foo id="3B3D3CAD1268FFDFD3E36F2DFD30DBD0" a="3392779302" b="Chiapas" c="Mexico">
<emphasis bold="true" pageId="3" pageNumber="120">Type locality.</emphasis>
</foo>
<emphasis bold="true" pageId="3" pageNumber="120">Other localities.</emphasis>
<foo id="3B3D3CAD1268FFDFD3E36F2D68FFDFD" a="3392779378" b="Baja California" c="Mexico">
<emphasis bold="true" pageId="3" pageNumber="120">Type locality.</emphasis>
</foo>

and I have selected the above like so

const elements = $('foo')
for (let i = 0; i < elements.length; i++) {
   const e = elements[i]
   console.log($(e).html())
}

I get

<emphasis bold="true" pageId="3" pageNumber="120">Type locality.</emphasis> 
<emphasis bold="true" pageId="3" pageNumber="120">Type locality.</emphasis>

But I want

<foo id="3B3D3CAD1268FFDFD3E36F2DFD30DBD0" a="3392779302" b="Chiapas" c="Mexico"></foo>
<foo id="3B3D3CAD1268FFDFD3E36F2D68FFDFD7" a="3392779378" b="Baja California" c="Mexico"></foo>

Solution

  • console.log($(e).prop('outerHTML')) does the trick