需移除特定標籤 (如 <p>) 但保留其內部文字與子元素。直接 remove() 會連內容一起刪除,需用 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'); // 限定範圍
.unwrap() 方法更簡潔:
// 移除所有 p 的父包裹 (若 p 是直接子元素)
$('p').unwrap();
// 移除特定父層
$('p').parent('.wrapper').unwrap();
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() 僅移除該層標籤,內層標籤保留。若需完全扁平化,需遞迴處理。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();
}
- 上一篇程序編程: jQuery 實現側邊欄跟隨捲動固定(Sticky Sidebar)
- 下一篇程序編程: jQuery 判斷捲動條到達頂部/底部完整指南