簡體   English   中英

如何僅刪除直接父p標簽

[英]How to remove only the immediate parent p tag

我使用的是富文本編輯器(ckeditor),它將所有內容包裝在<p>標記中,甚至是圖像。 因此,當我插入圖像時,它會執行以下操作:

<div id="description">
    <p>Some introduction the user wrote</p>
    <img src="/path/to/image" />
    <p>Some text here that the user wrote</p>
    <p>Oops an inline image <img src="/path/to/image" /></p>
    <p>More stuff that the user wrote.</p>
</div>

我只想刪除#description div中所有圖像上的包裝<p>標簽。

我嘗試了$('img').unwrap()但是它剝奪了所有<p>標簽。

我也嘗試了$('img').replaceWith(function() { return $(this).contents(); }); 從DOM中刪除了整個圖像。

有什么想法怎么做? 如果您設法使JSFiddle正常工作,將不勝感激。

$(document).ready(function(){

    $("#description p img").unwrap();

});

你可以試試這個-

$('img').each(function (){
    var $img = $(this);
    var $p = $img.parent('p');
    if($p.val() != undefined)
    {
        $p.replaceWith($img);
    }
});

我在這里添加了對父標記的檢查。 因此,如果它是'p' ,那么只有它下面的'img'可以代替。 如果您想要的是'p'下的全部內容,則將最后一行替換為-

$p.replaceWith($p.html());

JSFiddle: http : //jsfiddle.net/t7snLne2/

暫無
暫無

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

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