This is some text that is being written

Remove tag around node text with javascript

If I have HTML that looks like this:

<div id="text">
      This is some text that is being written <span class="highlight">with
      a highlighted section</span> and some text following it.
</div>

And I want to remove the "span", leaving the text node inside, how would I do it? I tried using jQuery to do the following:

wrap = $('.highlight');
wrap.children().insertBefore(wrap);
wrap.remove();

But this does not work, I suppose, because the children return an empty set, since there is only node text there. So all that happens is that the range and its contents are deleted.

I am also open to alternatives to my approach. What happens is that my code actually creates this range when the user selects a block of text. It wraps the selected text in the gap to visually distinguish it. I need to remove the gap later, although due to some quirks with how the mozilla range object works.

EDIT: "#text", .

+5
8

:

var wrap = $('.highlight');
var text = wrap.text();
wrap.replaceWith(text);
+18

(function($) {   
    $.fn.tagRemover = function() {           
        return this.each(function() {            
        var $this = $(this);
        var text = $this.text();
        $this.replaceWith(text);            
        });            
    }    
})(jQuery);

:

$('div span').tagRemover();

- /edit URL-,

+6

:

wrap = $('.highlight');
wrap.before(wrap.text());
wrap.remove();
+3

, , .highlight.

content = $(".highlight").contents();
$(".highlight").replaceWith(content);
+3
element = document.getElementById("span id");
element.parentNode.insertBefore(element.firstChild, element);
element.parentNode.removeChild(element);
+1

text.replace(/</? [^ > ] + ( > | $)/g, "");

0

it would be much easier to just change the span class than to actually delete it. You can use pure javascript:

document.getElementById("span id").className="";

Or jquery toggleClass function:

 $("element").toggleClass("highlight");

In addition, best practices say that you should not use class names that imply style, such as highlighting. Instead, try to emphasize: D

0
source

Best U-Turn Plugin:

$.fn.unwrap = function() {
  this.parent(':not(body)')
    .each(function(){
      $(this).replaceWith( this.childNodes );
    });

  return this;
};

from Ben Alman

-1
source

All Articles