1

I'm very new to JS and HTML. I would like to remove an element from the page as soon as the page is loaded. This is my simple HTML code:

<html>
    <head>
    </head>
        <body>
        <div id="trapParent"><a id="trap" href='/trap/removeByJS'> Javascript removal </a></div>
        <script>
        function timeout() {
            setTimeout(function () {
                timeout();
            }, 1000);
        }
        timeout();
        var parent = document.getElementById('trapParent');
        var child = document.getElementById('trap');
        while (child & parent){
        parent.removeChild(child);
        parent = undefined;
        child = undefined;
}
        </script>
    </body>
</html>

But when I open the page I can still get a reference to the link on the page; when I get the value of document.getElementById('trap');, it returns the link which means that it is still in the DOM and I can see that the link is still there. Am I missing something here?

I added the timeout function to make sure that the script will run after the page is loaded.

j08691
  • 204,283
  • 31
  • 260
  • 272
Alex
  • 1,914
  • 6
  • 26
  • 47
  • you cant block main thread with setTimeout, its async, you need promise to do that. Also change child & parent to child && parent if you're checking if they are defined – Chris Li Sep 08 '18 at 15:38
  • How can I remove the element then? because if it is not loaded, then document.getElementById('trap'); would be nothing. – Alex Sep 08 '18 at 15:40
  • 1
    change child & parent to child && parent worked for me, you dont really need the settimeout. js is going to run after page loads because its at the bottom of body – Chris Li Sep 08 '18 at 15:42
  • 1
    Take a look at [this](https://stackoverflow.com/questions/807878/javascript-that-executes-after-page-load). If you remove the element in an onLoad function you should be fine. – Carle B. Navy Sep 08 '18 at 15:42
  • Nice, thanks, guys! remove onload worked for me. – Alex Sep 08 '18 at 15:55

1 Answers1

0

Thanks to above answers, the following worked for me:

<html>
    <head>
    </head>

    <body onload = "removelink();">
        <div id="trapParent"><a id="trap" href='/trap/removeByJS'> disables Javascript </a></div>

        Hey!
         <script>
        function removelink( ){
                var parent = document.getElementById('trapParent');
                var child = document.getElementById('trap');
                while (child && parent){
                        parent.removeChild(child);
                        parent = undefined;
                        child = undefined;
                }
        }
        </script>

</body>
</html>
Alex
  • 1,914
  • 6
  • 26
  • 47