Reputation: 7573
I'm using a rich text editor (ckeditor) which wraps everything in <p>
tags, even images. So when I insert an image it does this:
<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>
I just want to remove the wrapping <p>
tag on all images that are within the #description
div.
I tried $('img').unwrap()
but it stripped all the <p>
tags.
I also tried $('img').replaceWith(function() { return $(this).contents(); });
which removed the entire image from the DOM.
Any ideas how to do it? A JSFiddle would be really appreciated if you manage to get it working.
Upvotes: 0
Views: 470
Reputation: 4484
You can try this -
$('img').each(function (){
var $img = $(this);
var $p = $img.parent('p');
if($p.val() != undefined)
{
$p.replaceWith($img);
}
});
I have added a check for parent tag here. So, if it is 'p'
, then only it shall be replaced with 'img'
below it. If what you want are the entire content under 'p'
, then replace the last line by this -
$p.replaceWith($p.html());
JSFiddle: http://jsfiddle.net/t7snLne2/
Upvotes: 1