0

I would like to remove everything inside of an HTML-section, using JS, but there are <script>-tags inside of the section and JS does not remove them, why and how can I do this?

Code:

document.querySelector(".desktop_only").remove();
<section class="desktop_only">
  The JS removes this text.
  <script> alert("It does not remove the alert, why?"); </script>
</section>

3
  • 5
    “It does not remove the alert, why?” - because the alert has already happened, before you remove code even runs. Removing the script element after it has already been executed, does not make whatever it did, become undone again. Commented Jan 11, 2021 at 13:55
  • @CBroe Ah, ok… Thank You! Commented Jan 11, 2021 at 13:56
  • 1
    I'm guessing that the alert() has already been put in the event queue when the remove() command runs. After that, the remove() code runs. And then finally the event queue is processed. Commented Jan 11, 2021 at 13:57

1 Answer 1

1

The problem is HTML scripts are usually run first, then come any included scripts at the bottom of the HTML, so the alert script is probably removed after it already ran. It would be helpful if you added a codepen.io link!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.