简体   繁体   中英

Completely remove element / tag from DOM with JS or jQuery?

I am trying to remove empty H1 tags from my FE environment using JS. After I remove it bots and crawlers still see these tags = they are still visible via Page Source, the DOM nodes are loaded ect..

Is there a way to completely remove an element from the DOM?

My html is this:

<a href="/link"><img src="banner.jpg" title="Title" />
  <h1 class="nivo-h1-title">
    <span></span>
  </h1>
</a>

Firstly i tried jQuery method:

$( document ).ready(function() {
    $( ".nivo-h1-title" ).remove();
});

This way the elements are removed from final HTML but still are present when you view the page via Page Source and Robots / Crowlers still see them. I researched a lot and tried pure Javascript method using code from this link Remove all child elements of a DOM node in JavaScript - removeChild with parentNode:

var elements = document.getElementsByClassName('nivo-h1-title');
while(elements.length > 0){
        elements[0].parentNode.removeChild(elements[0]);
}

But alas the html elements are still in the DOM = still can be seen via Page Source.

I already checked this Completly remove a tag from the source and others, but IS there a way to do this - completely remove elements from source?

JavaScript is executed after the initial page is served to the client. No way around that. You have to move that logic from the client-side JavaScript to a server-side language like eg PHP. That way it will be removed before the page is served.

The topic you found already had 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM