JavaScript is executed "inline", i.e. in the order in which it appears in the DOM (if that wasn't the case, you could never be sure that some variable defined in a different script was visible when you used it for the first time).

So that means in theory you could have a script at the beginning of the page (i.e. first <script> element) which looks through the DOM and removed all <script> elements and event handlers inside of your <div> .

But the reality is more complex: DOM and script loading happens asynchronously. This means that the browser only guarantees that a script can see the part of the DOM which is before it (i.e. the header so far in our example). There are no guarantees for anything beyond (this is related to document.write() ). So you might see the next script tag or maybe, you don't.

You could latch to the onload event of the document - which would make sure you got the whole DOM - but at that time, malicious code could have already executed. Things get worse when other scripts manipulate the DOM, adding scripts there. So you would have to check for every change of the DOM, too.

So @cowls solution (filtering on the server) is the only solution which can be made to work in all situations.