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!

+3


source to share


5 answers


This should do what you are looking for:

$('p > img').removeAttr('height').removeAttr('width').unwrap();

      



This will work for <img>

, wrapped in <a>

:

$('p > a > img').removeAttr('height').removeAttr('width').parent().unwrap();

      

+7


source


You can remove the attached node with .unwrap()

, and the attributes with removeAttr()

...



$('.content > p > img').unwrap()
                       .removeAttr('width height')

      

+3


source


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 = '';
});

      

+2


source


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.

+1


source


you can try something like this:

$('p + img').replaceWith(function() {
  return $(this).contents().removeAttr('width height');
});

      

stole the last bit from above

0


source







All Articles