【发布时间】:2021-01-12 16:16:40
【问题描述】:
所以我有这个小 chrome 扩展项目,我试图弄清楚如何在包含特定单词的“h2”元素之后找到页面上的第一个“ul”元素。
网页外观示例...
<div>
<h2>Foo</h2> // find the first <h2> tag containing "Foo"
<ul></ul> // find the first <ul> tag that comes after the <h2>
</div>
然而,不同页面代码的性质意味着它可能看起来更像这样......
<h2>Foo</h2> // find the first <h2> tag containing "Foo"
<div>
<ul></ul> // find the first <ul> tag that comes after the <h2>
</div>
甚至……
<div>
<h2>Foo</h2> // find the first <h2> tag containing "Foo"
</div>
<div>
<ul></ul> // find the first <ul> tag that comes after the <h2>
</div>
我可以通过...获取包含“foo”的“h2”元素
let hTags = document.querySelectorAll("h2");
let hTag;
for (var i = 0; i < hTags.length; i++) {
if (/foo/i.test(hTags[i].textContent)) {
hTag = hTags[i];
break;
}
}
但这就是我卡住的地方,我不知道如何搜索找到的“h2”标签后面的其余 DOM。兄弟选择器不起作用,因为“h2”和“ul”可能不在同一个元素中。
作为 chrome 扩展也排除了使用 jQuery 之类的东西。
有人知道这是否可能吗?任何想法将不胜感激!
【问题讨论】:
-
这可能会有所帮助stackoverflow.com/questions/1276753/… 它建议使用xpath,应该有办法做到这一点
标签: javascript google-chrome dom