简体   繁体   中英

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.

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

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

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

This works:

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

This will do what you want, and also preserve any tags within the .highlight span.

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

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

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

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

Or jquery's toggleClass function:

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

Also, best practices say that you shouldn't use class names that imply a style, like highlight. Try "emphasized" instead. :D

A better unwrap plugin:

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

  return this;
};

from Ben Alman

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM