将一个元素包装在一个新元素的原处

Wrapping an element inside a new element right where it is

我有一个包含许多文本节点、段落和图像的内容。我想将所有图像标签放在父 div 中。好吧,我认为没有直接的方法可以做到这一点(我的意思是 jQuery)。我应该如何处理元素的这种位移。以下示例说明了我的意图:

原始内容:

<div id='content'>
  Here are some texts.
  A second line.
  <a href='http://google.com'>Click Here!</a>
  Another Line.
  <img src='image.jpg' />
  Another another line.
  <img src='secondImage.jpg' />
  Last line and many more to come.
</div>

处理后:

<div id='content'>
  Here are some texts.
  A second line.
  <a href='http://google.com'>Click Here!</a>
  Another Line.
  <div class='image-parent'>
    <img src='image.jpg' />
  </div> 
  Another another line.
<div class='image-parent'>
  <img src='secondImage.jpg' />
</div> 
  Last line and many more to come.
</div>

唯一不同的是,现在每个图像都有一个新的 div 包装。

使用 .wrap() 将 HTML 结构包裹在每个元素周围。

$("#content > img").wrap("<div class='image-parent'></div>");
.image-parent {
    border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='content'>
  Here are some texts.
  A second line.
  <a href='http://google.com'>Click Here!</a>
  Another Line.
  <img src='image.jpg' />
  Another another line.
  <img src='secondImage.jpg' />
  Last line and many more to come.
</div>