如何确定 CheerioElement 是否为标题

问题描述

我想确定 CheerioElement 是否属于标题类型。我可以用这样的 html 元素来做到这一点:

const h = document.getElementById('h1');
const p = document.getElementById('p');

const isheading = e => e instanceof HTMLheadingElement

console.log(isheading(h));
console.log(isheading(p));
<h1 id="h1">heading</h1>
<p id="p">Paragraph</p>

但是我找不到任何关于如何从 Cheerio 中提取 HTML 元素的文档。我不知道这是否可行 - 也许 Cheerio 不会像访问实际 DOM 那样构造元素,因此不可能以这种方式使用原型。

是否可以确定 CheerioElement 是否为标题

解决方法

您可以将 .html() 与您的cheerio 元素一起使用。它将返回一个字符串,对于标题,它将返回 "Heading"

const $ = cheerio.load('<h1 id="h1">Heading</h1><p id="p">Paragraph</p>');
const h = $('h1');
const p = $('p');

const isHeading = e => e === 'Heading';

console.log(isHeading(h.html()));
console.log(isHeading(p.html()));
,

它与浏览器 HTML 元素不同(nodejs 没有实现 DOM),你可以使用 parse5,它是这些元素的cheerio 实现:

const isHeading = el => !!el.tagName?.match(/^h\d/)

$('*').get().map(el => isHeading(el))