In each .content-cont I'm trying to move the .media-cont before the nearest .middle but I can't make it work. I'm sure it's a dumb mistake but I've tried to figure it out and the best I can do is that all the .media-cont get inserted before the middle .middle p tag
Here's my code...
$('.content-cont').each((i, el) => {
let $p = $(el).find('p');
let mid = Math.floor($p.length / 2);
$p.eq(mid).addClass('middle');
});
$('.content-cont').each(function(i, e) {
$e = $(e);
let img = $('.media-cont');
$e.find(img).insertBefore($(this).closest($('.middle')));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="content-cont">
<div class="media-cont"></div>
<div class="text-cont">
<p>Some text</p>
<p class="middle">Some text</p>
<p>some text</p>
</div>
</div>
<div class="content-cont">
<div class="media-cont"></div>
<div class="text-cont">
<p>Some text</p>
<p class="middle">Some text</p>
<p>some text</p>
</div>
</div>
<div class="content-cont">
<div class="media-cont"></div>
<div class="text-cont">
<p>Some text</p>
<p class="middle">Some text</p>
<p>some text</p>
</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You are overthinking it
I assume I could remove the hardcoded
$('.content-cont').each((i, el) => {
let $p = $(el).find('p');
let mid = Math.floor($p.length / 2);
$p.eq(mid).addClass('middle');
$('.media-cont',el).insertBefore($('.middle',el)); // or use the eq here too
});
.middle { color: red }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="content-cont">
<div class="media-cont">Media</div>
<div class="text-cont">
<p>Some text</p>
<p>Some text</p>
<p>some text</p>
</div>
</div>
<hr/>
<div class="content-cont">
<div class="media-cont">Media</div>
<div class="text-cont">
<p>Some text</p>
<p>Some text</p>
<p>Some text</p>
<p>Some text</p>
<p>some text</p>
</div>
</div>
<hr/>
<div class="content-cont">
<div class="media-cont">Media</div>
<div class="text-cont">
<p>Some text</p>
<p>Some text</p>
<p>some text</p>
<p>Some text</p>
<p>Some text</p>
<p>some text</p>
<p>Some text</p>
<p>Some text</p>
<p>some text</p>
</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>