如何仅删除直接父p标记

时间:2015-02-19 21:25:13

标签: jquery

我正在使用富文本编辑器(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>

我只想删除<p> div中所有图片上的包裹#description标记。

我尝试$('img').unwrap(),但它删除了所有<p>代码。

我还尝试了$('img').replaceWith(function() { return $(this).contents(); });,它从DOM中删除了整个图像。

任何想法怎么做?如果你设法让它工作,那么JSFiddle真的很感激。

2 个答案:

答案 0 :(得分:2)

$(document).ready(function(){

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

});

答案 1 :(得分:1)

你可以试试这个 -

$('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/