簡體   English   中英

使用javascript刪除文本節點周圍的標記

[英]Remove tag around a text node using javascript

如果我有一些看起來像這樣的HTML:

<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>

我想刪除留下文本節點的“跨度”,我該怎么做呢? 我嘗試使用jQuery來執行以下操作:

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

但這不起作用我猜是因為孩子們返回一個空集,因為那里只有一個文本節點。 所以發生的一切都是跨度及其內容被刪除。

我也願意接受我的方法。 發生的事情是,當用戶選擇一個文本塊時,我的代碼實際上創建了該跨度。 它將選定的文本包裝在一個范圍內,以便在視覺上區分它。 我之后需要刪除跨度,因為mozilla的范圍對象的工作方式存在一些怪癖。

編輯:我不想替換'#text'的全部內容,因為它可能非常大。

你得到文本,並用它替換跨度:

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

將它包裝在一個插件中

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

然后像這樣使用

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

這里的工作演示 - 添加/編輯 URL以使用代碼

這有效:

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

這將執行您想要的操作,並保留.highlight范圍內的任何標記。

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

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

更改跨度的類比實際刪除它要容易得多。 你可以使用純javascript:

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

或者jquery的toggleClass函數:

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

此外,最佳實踐表明,您不應該使用暗示樣式的類名,例如高亮。 嘗試“強調”而不是。 :d

一個更好的解包插件:

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

  return this;
};

來自本·阿爾曼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM