Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove tag around a text node using javascript

If I have some 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 within, how would I go about doing that? I tried using jQuery to do the following:

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

But that doesn't work I'm guessing because children returns an empty set since there's only a text node in there. So all that happens is that the span and its contents are removed.

I'm also open to alternatives to my approach here. What's happening is that my code actually creates that span when a user selects a block of text. It wraps the selected text in a span to visually differentiate it. I need to remove the span afterward though because of some quirks with the way mozilla's range object works.

EDIT: I don't want to replace the entire content of '#text' by the way since it could be very large.

like image 332
Karim Avatar asked Sep 02 '09 20:09

Karim


3 Answers

You get the text, and replace the span with it:

var wrap = $('.highlight');
var text = wrap.text();
wrap.replaceWith(text);
like image 94
Pim Jager Avatar answered Oct 27 '22 17:10

Pim Jager


wrap it in a plugin

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

and then use like so

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

Working Demo here - add /edit to the URL to play with the code

like image 41
Russ Cam Avatar answered Oct 27 '22 15:10

Russ Cam


This works:

wrap = $('.highlight');
wrap.before(wrap.text());
wrap.remove();
like image 25
Gabriel Hurley Avatar answered Oct 27 '22 15:10

Gabriel Hurley