我正在尝试使用 JS 从我的 FE 环境中删除空的 H1 标签。在我删除它之后,机器人和爬虫仍然会看到这些标签 = 它们仍然通过页面源可见,DOM 节点已加载等..
有没有办法从 DOM 中完全删除元素?
我的html是这样的:
<a href="/link"><img src="banner.jpg" title="Title" />
<h1 class="nivo-h1-title">
<span></span>
</h1>
</a>
首先我尝试了 jQuery 方法:
$( document ).ready(function() {
$( ".nivo-h1-title" ).remove();
});
这样,这些元素就会从最终的 HTML 中删除,但当您通过页面源查看页面时,这些元素仍然存在,并且机器人/爬行者仍然可以看到它们。 我研究了很多,并使用此链接 Remove all child elements of a DOM node in JavaScript 中的代码尝试了纯 Javascript 方法。 - 删除Child与parentNode:
var elements = document.getElementsByClassName('nivo-h1-title');
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
但是 html 元素仍然在 DOM 中 = 仍然可以通过页面源代码看到。
我已经检查过这个Completly remove a tag from the source和其他人,但是 有有办法做到这一点 - 完全从源中删除元素吗?
最佳答案
JavaScript 在向客户端提供初始页面后执行。没有办法解决这个问题。您必须将该逻辑从客户端 JavaScript 转移到服务器端语言,例如PHP。这样,它将在页面提供之前被删除。
您找到的主题已经有 the right answer :
This is just how "view source" works in browsers. It shows you what came from the server (and usually re-queries it from the server [which may read it from cache]), not what is currently in the page.
To see what's currently in the page, you need to use the "Elements" or "DOM" tab in your browser's dev tools (usually opened via F12 or Ctrl+Shift+I). You can usually open it and move to a specific element by right-clicking that element on your page and choosing "Inspect element", so if you do that with your form after your $('.de').remove(); is run, you'll see the form without the .de elements in it.
关于javascript - 使用 JS 或 jQuery 从 DOM 中完全删除元素/标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54442103/