【问题标题】:How to determine if a CheerioElement is a heading如何确定 CheerioElement 是否是标题
【发布时间】:2021-05-06 08:53:16
【问题描述】:

我想确定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 是否为标题?

【问题讨论】:

    标签: javascript cheerio


    【解决方案1】:

    您可以将.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()));
    

    【讨论】:

      【解决方案2】:

      它与浏览器 HTML 元素不同(nodejs 不实现 DOM),您可以放入 parse5 中,它是那些的 Cheerio 实现:

      const isHeading = el => !!el.tagName?.match(/^h\d/)
      
      $('*').get().map(el => isHeading(el))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        相关资源
        最近更新 更多