select jquery 中 header 下方的文字

select text underneath header in jquery

我正在寻找一种动态 select 位于 header 下方的文本块的方法。

到目前为止,我已经尝试使用 $('#importantHeader').next()$('#importantHeader').next('p') 来做到这一点 但并非在所有情况下都有效。

例如,如果 header 包含在 <div> 或任何其他元素中,.next()-方法将不起作用,因为它 returns undefined.

现在我正在寻找一种方法,无论 header 和文本块是否包含在其他元素中,无论 DOM 结构如何。

就像说“select 页面显示在这个特定 header 正下方的任何文本块”

这里有一些 HTML-examples 解决方案需要配合使用:

<div>
    <div>
        <p>this is some random text I DON'T want to select</p>
    </div>
    <h4 id="importantHeader">This is the header I selected</h4>
    <div>
        <p>This is the text I want to select</p>
    </div>
    <h4 id="randomHeader">This is a header for the next section</h4>
    <div>
        <p>This is some random text I DON'T want to select</p>
    </div>
</div>

_

<p>this is some random text I DON'T want to select</p>
<h4 id="importantHeader">This is the header I selected</h4>
<div>This is the text I want to select</div>
<h4 id="randomHeader">header for next section</h4>
<p>This is some random text I DON'T want to select</p>

_

<div>
    <p>this is some random text I DON'T want to select</p>
</div>
<div><div><div>
    <h4 id="importantHeader">This is the header I selected</h4>
</div></div></div>
<div><div>
    <p>This is the text I want to select</p>
</div></div>
<div>
    <h4 id="randomHeader">header for next section</h4>
    <p>This is some random text I DON'T want to select</p>
</div>

是否有可能在 jQuery 或 Cheerio 中执行此操作?

next 是为 selecting 兄弟姐妹设计的函数,因此 'p' 不是“#importantHeader”的兄弟姐妹,而 'div' 是。

如果您尝试 select Text 节点,那么我不完全确定 JQuery 将如何 select 它们,但是这就是它的类型在香草 JS 中看起来像:

    // Select all elements from within the Body element (change the query to the container of the elements you want)
    var allTheTextNodes = Array.from(document.querySelectorAll("body *")).
        // filter each element's childNodes to ensure they are Text nodes and make sure the text isn't empty
        map(x=>Array.from(x.childNodes).filter(y=>y instanceof Text && y.nodeValue.replace(/[\r\t\n\s]/g,"") !== "")).
        // filter out any elements that didn't have any Text nodes and combine all the arrays together  
        filter(x=>x.length>0).reduce((a,c)=>a.concat(c),[]);
    
    console.log(allTheTextNodes);

然后,如果需要,您可以根据上述 Text 节点的 parent/ancestors 进行过滤。 然而,当文档中的元素越多时,这会变得非常重要。 我不确定这是否是您要找的东西。

我刚刚找到了适用于 cheerio 的 .next() 的有效解决方案。

正如@IRLotsEvil 提到的,.next() 只能 select 一个兄弟姐妹。所以我可以简单地创建一个循环,其中包含一个 运行 变量遍历父元素,直到它有一个包含文本节点的兄弟元素。

let rv = $(myHeader); // running variable
while(rv.next().text().trim() === '') {
    rv = rv.parent();
}
let sectionContent = rv.next().text().trim();

我没想到会这么简单,但到目前为止,它无误地完成了工作:)