Replace Paragraph Tags from Paragraphs With Only Single Floated Image with 该图像

Replace Paragraph Tags from Paragraphs With Only A Single Floated Image with that Image

我正在尝试弥补我的所见即所得,当不属于其他内容段落的一部分时,它用段落标记包围单个图像。这打破了我的花车。我想删除包含 only a single 图像的段落标签,并且仅当图像在img 标签。我看过示例,但它们似乎并没有专门针对该示例,并且会破坏我的其余内容。

我正在使用 Modx,但 jQuery 可能比在 php.

中创建自定义输出修饰符更容易(我 运行 v3)

所以:

<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>

变为:

<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">

使用简单的 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>