I have 2 different script tags:
<script>//</script>
<script>//data</script>
I wanted to remove the first one. so I used the following:
$("script").filter(":contains('//')").remove();
but the line above removes both.
How can i remove the first only.
CodePudding user response:
:contains means anywhere in the string
This will remove it if it ONLY contains "//"
$("script")
.filter(function () { return this.textContent.trim() === "//" })
.remove();
To remove the first script that has a // you can use .eq
$("script")
.filter(":contains('//')")
.eq(0)
.remove();
CodePudding user response:
.filter() method is return an array. so if you want to delete the first one you must select like an array.
$("script").filter(":contains('//')")[0].remove();
CodePudding user response:
function stripScripts(s) {
var div = document.createElement('div');
div.innerHTML = s;
var scripts = div.getElementsByTagName('script');
scripts[0].parentNode.removeChild(scripts[0]);
return div.innerHTML;
}
alert(
stripScripts('<span><script type="text/javascript">alert(\'foo\');<\/script> <script type="text/javascript">alert(\'foo\');<\/script><\/span>')
);