I am trying to compensate for my WYSIWYG, which surrounds single images with a paragraph tag when not part of a paragraph of other content. This breaks my floats. I would like to remove the paragraph tags containing only a single image and only if the image has an inline css float attribute in the img tag. I have seen examples, but they do not seem to target that specifically and would break the rest of my content.
I am using Modx, but jQuery would probably be easier (I run v3) than creating a custom output modifier in php.
So:
<p><img src="uploads/image.jpg" style="float: right; width: 235px; height: 225px; margin: 0px 0px 10px 10px;" alt="Description" width="235" height="225" class="d-none d-md-block"></p>
Becomes:
<img src="uploads/image.jpg" style="float: right; width: 235px; height: 225px; margin: 0px 0px 10px 10px;" alt="Description" width="235" height="225" class="d-none d-md-block">
This would be a quick and easy shot at it, using simple vanilla Javascript:
[...document.querySelectorAll('p')] // get all <p> as an array using spread syntax
.filter(p => // so we can use array filter function on the list
p.children.length === 1 // only those that have exactly one child element
&& // AND
p.firstElementChild.tagName === 'IMG' // which must be an <img>
&& // AND
p.firstElementChild.style.float // and needs to have an inline float
)
.forEach(p => p.replaceWith(p.firstElementChild)) // and replace each p with its only child
p {
border: 10px solid red;
}
<p>
<img src="uploads/image.jpg" style="float: right; width: 235px; height: 225px; margin: 0px 0px 10px 10px;" alt="Description" width="235" height="225" class="d-none d-md-block">
</p>
<br />
<p>
<img src="uploads/image.jpg" style="float: right; width: 235px; height: 225px; margin: 0px 0px 10px 10px;" alt="Description" width="235" height="225" class="d-none d-md-block">
<span>More than only the img</span>
</p>
<br />
<p>
<img src="uploads/image.jpg" style="width: 235px; height: 225px; margin: 0px 0px 10px 10px;" alt="image not floating" width="235" height="225" class="d-none d-md-block">
</p>
<br />
<p><b>No img inside p</b></p>