萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 移除指定 HTML 標籤但保留內容文字

需求場景

需移除特定標籤 (如 <p>) 但保留其內部文字與子元素。直接 remove() 會連內容一起刪除,需用 replaceWith() 替換為內容本身。

核心方法:html() + replaceWith()

<div id="content">
  <p>大家好,歡迎來到 jb51.net</p>
  這裡為大家提供最優秀的<a href="https://www.jb51.net/js">js</a>代碼和教程
</div>

<script src="jquery.min.js"></script>
<script>
$(function() {
  // 遍歷所有 p 標籤
  $("p").each(function() {
    var content = $(this).html(); // 取得內部 HTML (含子元素)
    $(this).replaceWith(content); // 用內容替換自身
  });
  
  // 結果:p 標籤消失,文字與 a 鏈接保留在原位
});
</script>

擴充:移除任意標籤並保留內容

// 通用函式:移除指定選擇器的標籤,保留內容
function unwrapTags(selector, context) {
  var $context = context ? $(context) : $(document);
  $context.find(selector).each(function() {
    $(this).contents().unwrap(); // jQuery 內建 unwrap() 即為此邏輯
  });
}

// 使用
unwrapTags('p');           // 移除所有 p
unwrapTags('span.bold');   // 移除 class=bold 的 span
unwrapTags('font', '#editor'); // 限定範圍

jQuery 內建 .unwrap() 方法

更簡潔:

// 移除所有 p 的父包裹 (若 p 是直接子元素)
$('p').unwrap(); 

// 移除特定父層
$('p').parent('.wrapper').unwrap();

原生 JavaScript 實現 (無依賴)

function unwrapElements(selector) {
  var elements = document.querySelectorAll(selector);
  elements.forEach(function(el) {
    var parent = el.parentNode;
    // 將子節點移至父節點,取代 el
    while (el.firstChild) {
      parent.insertBefore(el.firstChild, el);
    }
    parent.removeChild(el);
  });
}

// 使用
unwrapElements('p');

注意事項

  • 巢狀標籤:unwrap() 僅移除該層標籤,內層標籤保留。若需完全扁平化,需遞迴處理。
  • 事件綁定:被移除元素上的事件監聽器會隨元素移除而失效 (若用 jQuery 內建方法會自動清理)。
  • CSS 樣式影響:移除標籤可能改變樣式選擇器匹配 (如 p > span),需檢查樣式。
  • 語意化:移除語意標籤 (如 <article>, <section>) 可能影響 SEO 與無障礙。

應用範例:清理富文本編輯器冗餘標籤

function cleanEditorHTML(html) {
  var $wrap = $('
').html(html); // 移除空標籤 $wrap.find('p:empty, span:empty, div:empty').remove(); // 移除無屬性 span/font (保留內容) $wrap.find('span:not([class]):not([style]), font:not([class]):not([style])').contents().unwrap(); // 合併相鄰文字節點 $wrap[0].normalize(); return $wrap.html(); }
copyright © 萬盛學電腦網 all rights reserved