简体   繁体   中英

Remove <style> tag and <script> tag from plain HTML using Jquery

Here is my plain HTML code.

<style>
 /* style tag goes here*/
</style>
<form method="POST" action="#" id="_form_93_" class="_form _form_93 _inline-form  _dark" novalidate>
  <input type="hidden" name="u" value="93" />
  <input type="hidden" name="f" value="93" />
  <input type="hidden" name="s" />
  <input type="hidden" name="c" value="0" />
  <input type="hidden" name="m" value="0" />
</form>
<script type="text/javascript">
// script tag goes here
</script>

I want to remove <style></style> and <script></script> tag from HTML code so expected result will be.

<form method="POST" action="#" id="_form_93_" class="_form _form_93 _inline-form  _dark" novalidate>
  <input type="hidden" name="u" value="93" />
  <input type="hidden" name="f" value="93" />
  <input type="hidden" name="s" />
  <input type="hidden" name="c" value="0" />
  <input type="hidden" name="m" value="0" />
</form>

You can remove the tags using this

$('style, script').remove();

Styles will no longer show on screen and both HTML elements will dissapear from the DOM.

BUT, javascript code will still be executed if events have been attached before running the remove() code.

If you're only looking to clean some code returning by an ajax call (for example), it will work fine. If you want to clear the styles and javascript from the page you're already in, some Javascript code might already be attached to elements before you remove the script tag.

Check this fiddle for an example.

Using jQuery:

jQuery('style').remove();

jQuery('script').remove();

Using Plain JavaScript:

window.onload = function(){
    var getStyle = document.getElementsByTagName("style");
    getStyle[0].remove();
    var getScript = document.getElementsByTagName("script"); 
    getScript[0].remove();
}

Please find a working fiddle, which shows how to delete h1 tag, Link

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