Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Text and Tags with jQuery

Sounds easy, but it doest work: I want to remove ALL Content (text and tags) between two span tags:

<div class="comment-body" id="comment-body-parent-330">
<p><span id="sc_start_commenttext-330"></span>
Some Text<br>
Some Text<br>
Some Text</p>
<p>Some Text<span id="sc_end_commenttext-330"></span>
</p>
Some Text and Code
</div>

Everything you can find between span id "sc_start_commenttext-330" and span id "sc_end_commenttext-330" should be removed, like that:

    <p><span id="sc_start_commenttext-330"></span>
<span id="sc_end_commenttext-330"></span>
    </p>

I just try it with that Code, but it doenst work:

    jQuery("#sc_start_commenttext-330").
nextUntil("#sc_end_commenttext-330").
remove();

The code is generated by a CMS, so its not possivle to change the HTML.

Some ideas? Thanks a lot!

like image 252
user1711384 Avatar asked Dec 06 '12 10:12

user1711384


1 Answers

The following jQuery…

//Removing all non span elements
$('p').children().not('span').remove();​

//Removing text nodes
var forEach = [].forEach;
forEach.call($('p').contents(), function(node){
    if (node.nodeType === 3) {
      $(node).remove();
    }
});

results in…

<p><span id="sc_start_commenttext-330"></span></p>
<p><span id="sc_end_commenttext-330"></span></p>

edit: here is an alternative for-loop approach for removing the text nodes

//Removing text nodes
for (var i = 0, allNodes = $('p').contents(); i < allNodes.length; i++) {
    if (allNodes[i].nodeType === 3) {
      $(allNodes[i]).remove();
    }
}
like image 185
Stephan Bönnemann-Walenta Avatar answered Sep 29 '22 01:09

Stephan Bönnemann-Walenta