gpt4 book ai didi

javascript - 将元素包装在新元素的原处

转载 作者:行者123 更新时间:2023-11-28 18:29:43 25 4
gpt4 key购买 nike

我有一个内容,其中包含许多 TextNodes、段落和图像。我想将所有图像标签放在父 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>

关于javascript - 将元素包装在新元素的原处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38324803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com