我有一些来自数据库的HTML(我无法控制),它包含许多文本和图像。我需要在其中具有<a>
标记的第一个<img>
标记之前或之后插入特定元素。
这是HTML的示例:
<section class="main">
<p>Nokia 8 4GB RAM 64GB Dual Sim Phone</p>
<p>The Nokia 8 undergoes a rigorous 40-stage process of machining, anodizing and polishing to ensure its distinctive design pairs flawlessly with the polished aluminium unibody.</p>
<p>The ultimate in seamless unibody construction, Nokia 8 is designed to nestle perfectly in the palm of your hand.</p>
<a href="https://www.nokia.com">
<img src="https://cdn2.gsmarena.com/vv/bigpic/nokia-8-.jpg" />
</a>
<p>We offer 14 days money back guarantee in case of a change of mind. </p>
</section>
<div class="movethisdiv">I want to move this content</div>
据我所知,可以将
div
移到img
元素之前,但是显然它将永远无法工作,因为img被包装在锚标记中。那么,我如何让jQuery在其中具有图像的第一个锚元素之前插入div
?$(".movethisdiv").insertBefore( $("section.main").find("a > img").first());
上面的代码只会将
div
插入img
标记之前,但要插入a
元素内。我希望它在a
元素之前插入。 最佳答案
在.parent()
之后添加.first()
,如下所示:$(".movethisdiv").insertBefore( $("section.main").find("a > img").first().parent());