【问题标题】:JS select <ul> tag following an <h2> tag containing "foo"JS 在包含“foo”的 <h2> 标记之后选择 <ul> 标记
【发布时间】: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 之类的东西。

有人知道这是否可能吗?任何想法将不胜感激!

【问题讨论】:

标签: javascript google-chrome dom


【解决方案1】:

这应该可以解决问题:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>
      <h2>Foo</h2>
    </div>
    <div>
      <ul></ul>
    </div>

    <script>
      const regex = new RegExp('foo', 'i');
      const foundElements = [...document.querySelectorAll('* H2, UL')];
      const firstUL = foundElements
        .slice(1)
        .find(
          (el, i) => el.tagName === 'UL' && foundElements[i].tagName === 'H2' && regex.test(foundElements[i].innerText)
        );
      console.log(firstUL);
    </script>
  </body>
</html>

【讨论】:

  • 这是王牌!正是我需要的。关于如何调整它以查找包含“foo”的 h1、h2 和 h3 标签的任何想法?
  • 如果您希望它在包含“foo”的 H1、H2 或 H3 标签之后查找 UL,您只需将选择器更改为:.querySelectorAll('* H1, H2, H3, UL' )
猜你喜欢
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 2016-01-19
  • 2013-07-13
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
相关资源
最近更新 更多