根据previousElementSibling

时间:2016-03-23 17:36:29

标签: javascript

我正在编写一个脚本,用于选择从section元素下降的所有段落元素。我希望它排除所有具有标题标记的previousElementSibling的段落元素。

脚本的工作部分,我的测试console.logs是

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为空。

我也尝试添加:

&& prevElement != '<h3'>

到if条件以查看是否有效,以及'h3'/'H3'并且都没有。

有没有办法从初始document.querySelectorAll中排除h3 + p或者在if / then条件下过滤掉它?

注意:我不想在jQuery中执行此操作。

1 个答案:

答案 0 :(得分:2)

  

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

您可以使用选择器

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 || …