我正在编写一个脚本,该脚本选择从section元素派生的所有段落元素。我希望它排除所有具有heading标签的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
}
}
不过,我想做的是特别是排除任何以heading元素开头的段落元素。
当我运行上面的脚本时,console.log输出将正确列出所有内容。我无法弄清楚如何实际测试“” /“ h3” / etc的值。
我尝试使用其他一些属性,例如.localName和.nodeName。当我将它们添加到console.log时:
console.log(prevElement.localName);
console.log(prevElement.nodeName);
这两种情况都会在控制台中导致prevElement为null的错误。
我也尝试添加:
&& prevElement != '<h3'>
到if条件,看看它是否有效,以及'h3'/'H3',但没有一个起作用。
有没有办法从初始document.querySelectorAll中排除h3 + p或在if / then条件下将其过滤掉?
注意:我不想在jQuery中执行此操作。
最佳答案
有没有办法从初始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 || …
。