Reputation: 173
this is my code as default i want to remove script, comments and some text from this div using js and get final code below after the js mask
i found this code to remove script but it removes all the script i want to remove from this div only
$('script').each(function () {
$(this).remove();
});
My code:
<div class="data-content">
<!-- comment_beginning -->- Sponsored Links -
<br>
<script src="//data.js"></script>
<!-- comment -->
<script>
//some js
</script>
<br>
- Sponsored Links -<!-- /comment_beginning -->
<div>
<a href="d.jpg"><img title="example" src="world.jpg" alt="data" width="300" class="animation-data-type0-2"></a>
</div>
<p></p>
<p></p>
<p></p>
<!-- comment_after -->- Sponsored Links -
<br>
<script src="//data.js"></script>
<!-- comment -->
<script>
//some js
</script><!-- /comment_after -->
</div>
Final output:
<div class="data-content">
<div>
<a href="d.jpg"><img title="example" src="world.jpg" alt="data" width="300" class="animation-data-type0-2"></a>
</div>
<p></p>
<p></p>
<p></p></div>
Upvotes: 1
Views: 437
Reputation: 173
Solved
thanks for the help the text was still their and this is how i removed the text
$(".data-content").contents().filter(function () {
return this.nodeType === 3; // Text nodes only
}).remove();
Upvotes: 0
Reputation: 10175
You can use the following code to target all script tags that resides under the mentioned div.
$(".data-content script").each(function(){
var scriptElement = $(this);
scriptElement.remove();
});
Code for removing the comments:
var container = $(".data-content");
container.contents()
.filter(function(){ return this.nodeType == 8; })
.remove();
Upvotes: 1
Reputation: 7015
Use $('.data-content').find('script')
to select only script tags
. To remove comments iterate through the content and remove like below
$('.data-content').find('script').each(function () {
$(this).remove();
});
$('.data-content').contents().each(function() {
if(this.nodeType === Node.COMMENT_NODE) {
$(this).remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My code:
<div class="data-content">
<!-- comment_beginning -->- Sponsored Links -
<br>
<script src="//data.js"></script>
<!-- comment -->
<script>
//some js
</script>
<br>
- Sponsored Links -<!-- /comment_beginning -->
<div>
<a href="d.jpg"><img title="example" src="world.jpg" alt="data" width="300" class="animation-data-type0-2"></a>
</div>
<p></p>
<p></p>
<p></p>
<!-- comment_after -->- Sponsored Links -
<br>
<script src="//data.js"></script>
<!-- comment -->
<script>
//some js
</script><!-- /comment_after -->
</div>
Upvotes: 1