👌
Node.js製HTMLパーサ「cheerio」の出力結果からhtmlやbodyタグを除く
2023/1/31追記: cheerio.load()の第三引数をfalseにすればOK
このissueのコメントの通り、cheerio.load(HTML, options, ここ)をfalseにすれば出力結果に<html>や<head>、<body>が自動で付与されることは無くなりました。
const $ = cheerio.load('<div>Hello</div>', options, false);
console.log($.html());
// => "<div>Hello</div>"
修正前の内容
Node.jsのHTMLパーサcheerioを使うと、特定のHTML(DOM)だけを直感的に書き換えることができます。
import cheerio from 'cheerio';
// 読み込む
const $ = cheerio.load('<h1 class="heading">Foo</h1>');
// DOMを好きなように操作
$('.heading').text('Bar');
$('.heading').addClass('red');
// 変換後のHTMLを取得
const result = $.html();
console.log(result);
// <html><head></head><body><h1 class="heading red">Bar</h1></body></html>
問題は出力結果に<html>や<head>、<body>が自動的に付与されてしまうということです。一部のみを書き換えたいときにはこれでは困ります。
該当するissueには解決策が載っていないのですが、Gatsbyのソースコードを見てみると以下のような形で対応されていました。
$(`body`).html() // fix for cheerio v1
というわけで最初のサンプルで<html>や<body>が付与されないように書き直すと次のようになります。
import cheerio from 'cheerio';
const $ = cheerio.load('<h1 class="heading">Foo</h1>');
$('.heading').text('Bar');
$('.heading').addClass('red');
const result = $('body').html();
console.log(result);
// <h1 class="heading red">Bar</h1>
Discussion