Search code examples
javascripthtmlabstract-syntax-treecheerio

How to make cheerio not to self-close tags?


The output of this code with cheerio:

  <div id="some"></div>

Returns as self-closing tag:

 <div id="some"/>

Is it possible to change that behavior (self-closing)? I don't want to use that.

I tried those options but doesn't seems that affect the output:

  { decodeEntities: false, xmlMode: true, recognizeSelfClosing: false },

Is any other solution maybe available?

import "./styles.css";
import { CheerioAPI, load } from "cheerio";

console.clear();

const doc = load(
  `
  <div id="some"></div>
`,
  { decodeEntities: false, xmlMode: true, recognizeSelfClosing: false },
  false
);

console.log({
  after: doc.html({
    decodeEntities: false,
    xmlMode: true,
    recognizeSelfClosing: false
  })
});

codesandbox.io


Solution

  • You have set xmlMode:true you need to set xmlMode:false and remove recognizeSelfClosing: false

    import "./styles.css";
    import { CheerioAPI, load } from "cheerio";
    
    console.clear();
    
    const doc = load(
      `
      <div id="some"></div>
    `,
      { decodeEntities: false, xmlMode: true, recognizeSelfClosing: false },
      false
    );
    
    console.log({
      after: doc.html({
        decodeEntities: false,
        xmlMode: false
      })
    });
    

    This will give you the output in the console as

    {after: "
      <div id="some"></div>
    "}