如何在 Mutation Observer 中定位特定标签

发布于 2025-01-14 13:58:54 字数 942 浏览 1 评论 0原文

我正在尝试这样的事情:

var pin = document.querySelector("#notice ul li div p a");

这个想法是缩小观察者的范围并仅过滤中的相关元素在这种情况下,嵌套标签内的所有“a”。 ID“notice”是唯一具有 ID 的标签,然后我需要选择第一个“ul”,然后是“li”,依此类推,直到到达我感兴趣的“a”。

将其传递给观察者,它使用以下选项进行侦听:

const config = { attribute: true, childList: true, subtree: true };

所以我有 observer.observe(pin, config);代码> 和相关let Observer = new MutationObserver(mutations => { 但是我一定做错了什么,因为它没有拉动任何东西。只有当我使用这个时它才有效:

var pin = document.querySelector( "#notice");

如何将观察者限制为仅我感兴趣的相关部分?我知道我可以监视整个文档正文,但会影响 CPU 负载并执行不必要的操作,因为我需要这样做仅隔离在特定标签中。

这是我正在处理的示例 HTML

<section id="notice">
<ul>
   <li>      
      <div>  
          <p>
            <a href="locale.html?58651456454">Translate</a>
      </p>
      </div>
   </li>
</ul>
</section>

I'm trying something like this:

var pin = document.querySelector("#notice ul li div p a");

The idea is to narrow down the observer and filter only the relevant element(s) in this case all 'a' inside the nested tags. The ID 'notice' is the only tag with an ID, I then need to select the first 'ul' then 'li' and so on, until I reach the 'a' I'm interested in.

Passing this to the observer, which is listening with the following options:

const config = { attributes: true, childList: true, subtree: true };

So I have the observer.observe(pin, config); and relative let observer = new MutationObserver(mutations => { However I must be doing something wrong sing it is not pulling anything. It only works if I use this:

var pin = document.querySelector("#notice");

How can I limit the observer to only relevant portion I'm interested in? I know I could monitor the whole document body, but will affect CPU load and do unnecessary operations since what I need to isolate in just a specific tag.

this is the sample HTML I'm workin on

<section id="notice">
<ul>
   <li>      
      <div>  
          <p>
            <a href="locale.html?58651456454">Translate</a>
      </p>
      </div>
   </li>
</ul>
</section>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文