Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How ignore cheerio from turn attributes to lowercase?

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 :(

like image 823
Jon Sud Avatar asked Sep 14 '25 13:09

Jon Sud


1 Answers

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>
*/
like image 127
Shlomi Levi Avatar answered Sep 16 '25 04:09

Shlomi Levi