简体   繁体   English

去掉<style> tag and <script> tag from plain HTML using Jquery

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

Here is my plain HTML code. 这是我的纯HTML代码。

<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. 我想从HTML代码中删除<style></style><script></script>标记,以便达到预期的效果。

<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. 样式将不再显示在屏幕上,并且两个HTML元素都将从DOM中消失。

BUT, javascript code will still be executed if events have been attached before running the remove() code. 但是,如果在运行remove()代码之前附加了事件,则仍将执行javascript代码。

If you're only looking to clean some code returning by an ajax call (for example), it will work fine. 如果您只是想清理一些通过ajax调用返回的代码(例如),它将可以正常工作。 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. 如果要清除已进入页面的样式和javascript,则在删除script标记之前,某些Javascript代码可能已附加到元素上。

Check this fiddle for an example. 查看这个小提琴作为示例。

Using jQuery: 使用jQuery:

jQuery('style').remove();

jQuery('script').remove();

Using Plain JavaScript: 使用纯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 请找到一个有效的小提琴,其中显示了如何删除h1标签, 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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