排除基于先前ElementSibling的元素

Excluding an Element based on previousElementSibling

本文关键字:元素 ElementSibling 于先前 排除      更新时间:2023-09-26

我正在编写一个脚本,该脚本选择从section元素派生的所有段落元素。我希望它排除所有具有heading标记的previousElementSibling的段落元素。

脚本的工作部分,以及我的测试控制台.log是

var allParagraphs = document.querySelectorAll('section > p');
var firstParagraph = allParagraphs[0];
for (i=0; i < allParagraphs.length; i++) {
    var prevElement = allParagraphs[i].previousElementSibling;
    console.log(prevElement);
    if (i !=0 && i != allParagraphs.length && i % 3 == 0 ) {
        // Work Magic on the Paragraph Elements
    }
}

不过,我想做的是排除任何前面有标题元素的段落元素。

当我运行上面的脚本时,我的console.log输出将正确列出所有内容。我不知道如何实际测试"/"h3"/等的值。

我尝试使用其他一些属性,如.localName和.nodeName。当我将它们添加到console.log时:

console.log(prevElement.localName);
console.log(prevElement.nodeName);

这两种情况都会导致控制台中出现prevElement为null的错误。

我还试着添加:

&& prevElement != '<h3'>

如果条件,看看这是否有效,以及"h3"/"h3",但都没有。

有没有办法从初始文档中排除h3+p。querySelectorAll或在if/then条件中过滤掉它?

注意:我不想在jQuery中这样做。

有没有办法将h3+p从初始document.querySelectorAll中排除?

你可以使用选择器

section > p:first-child, section > *:not(h1):not(h2):not(h3):not(h4):not(h5):not(h6) + p

…还是在if/then条件下过滤掉?

您使用prevElement.nodeName != "h3"的方法很好,但您需要注意作为其部分中第一个元素且没有.previousElementSibling的段落。只测试prevElement == null || …