gpt4 book ai didi

javascript - 排除基于 previousElementSibling 的元素

转载 作者:行者123 更新时间:2023-12-02 14:51:06 25 4
gpt4 key购买 nike

我正在编写一个脚本,该脚本选择从节元素下降的所有段落元素。我希望它排除具有标题标记的 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 为 null 的错误。

我还尝试添加:

&& prevElement != '<h3'>

查看 if 条件是否有效,以及“h3”/“H3”,但没有一个有效。

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

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

最佳答案

Is there a way to either exclude h3+p from the initial document.querySelectorAll?

您可以使用选择器

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

…or to filter it out in the if/then condition?

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

关于javascript - 排除基于 previousElementSibling 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36185028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com