Remove paragraph tags that have an img child, but don't remove the img
I am working with a CMS (ExpressionEngine) that wraps paragraph tags around images. I am using responsive images (max-width: 100%) and since I also define width in my paragraphs this causes problems. I would like to use jQuery to remove paragraph tags that are wrapped around images. I would also like to have the width and height properties removed from the images as they are not needed in combination with max-width: 100%.
Here's an example of the HTML before the change:
<div class="content">
<p>Hello! This is text content in a blog post.</p>
<p><img src="hello.jpg" width="300" height="300" alt="Hello!" /></p>
<p>This is more text content in the blog pst.</p>
</div>
... and this is what I would like to get:
<div class="content">
<p>Hello! This is text content in a blog post.</p>
<img src="hello.jpg" alt="Hello!" />
<p>This is more text content in the blog pst.</p>
</div>
I could just change the format of the ExpressionEngine field from "XHTML" to "none", but this requires a human to submit content to write HTML, which I would rather avoid. Thanks for any help!
source to share
You can remove the attached node with .unwrap()
, and the attributes with removeAttr()
...
$('.content > p > img').unwrap()
.removeAttr('width height')
You can use jQuery.unwrap and reset the height / width while you're at it:
$('p > img').each(function() {
$(this).unwrap();
this.height = '';
this.width = '';
});
source to share
Use a selector to find p tags with images in them, then pull this node and return it:
var $img = $('p').find('img');
$img.parent().replaceWith($img);
$img.css('height','');
$img.css('width','');
This is untested, so I'm not entirely sure if the logic is correct, but these are the main functions / flow you want to use.
source to share