How ignore cheerio from turn attributes to lowercase?

Viewed 319

How to tell cheerio NOT to change the attributes to lowercase?

Currently, cheerio turns fooBar into foobar. how to NOT do it?

codesandbox.io

const cheerio = require("cheerio");

const html = `
  <div>
   <h4></h4>
   <img src="">
   <input>
   <p fooBar></p>
  
  </div>

`;

const $ = cheerio.load(html);

const output = $.html();

console.log({ output });

I try to add lowerCaseAttributeNames according to answer in github but this not help:

const $ = cheerio.load(html, { lowerCaseAttributeNames: false });

The results:

<html><head></head><body><div>
   <h4></h4>
   <img src>
   <input>
   <p foobar></p> <------------------foobar. expected: fooBar
  
  </div>

</body></html>

I try with xmlMode, but it creates closing problem:

 <div>
   <h4/>
   <img src="">
   <input>
   <p fooBar=""/>
  
  </input></img></div>

UPADTE

I searched the lowerCaseAttributeNames in Github, but it only exist in the types, not sure it have impact on the code :(

2 Answers

Cheerio is using parser5 by default and the lowerCaseAttributeName is a htmlparser2 attribute.

You could try to load the htmlparser2 at the start as indicated in their github page:

// Usage as of htmlparser2 version 3:
const htmlparser2 = require('htmlparser2');
const dom = htmlparser2.parseDOM(document, options);

const $ = cheerio.load(dom);

After I did some digging into cheerio source code and many other libraries, I understand you can use cheerio to get what you want.

first, you should load the content by xmlMode:true and use xmlMode:false when you call to html():

const $ = cheerio.load(html, { xmlMode: true });
const output = $.html({ xmlMode: false });

The full code is also on codesandbox.io

const cheerio = require("cheerio");

console.clear();

const html = `
  <div>
   <h4></h4>
   <img src="">
   <input>
   <p fooBar></p>
  
  </div>

`;

const $ = cheerio.load(html, { xmlMode: true, lowerCaseAttributeNames: false });

const output = $.html({ xmlMode: false });

console.log({ output });

/*
<div>
   <h4></h4>
   <img src>
   <input>
   <p fooBar></p>
  
  </div>
*/
Related