What i'm trying to do is first check to see if in an unordered list the first element is an image, if it is an image then either move the first child to be the second child or if it's easier move the second child to be the first.
<ul>
<li><img src="test.img" alt=""></li>
<li><p>text</p></li>
<li><p>text2</p></li>
</ul>
<ul>
<li><p>text</p></li>
<li><img src="test.img" alt=""></li>
<li><p>text2</p></li>
</ul>
And then the finished result would look like this:
<ul>
<li><p>text</p></li>
<li><img src="test.img" alt=""></li>
<li><p>text2</p></li>
</ul>
<ul>
<li><p>text</p></li>
<li><img src="test.img" alt=""></li>
<li><p>text2</p></li>
</ul>
How would I target the first list specifically and move that one without moving the second list? So only targeting the first unordered lists list item and moving it based on the if statement? I've tried using insertBefore but think I might be using it wrong?
Looking to not use jquery if possible and appreciate any help!
You can loop through all the <ul>
elements. Check if the first <li>
children has an <img>
tag. If it does then move first <li>
after the second <li>
.
Please review code example below:
$(function() {
$('ul').each(function() {
var $first = $(this).children().first();
// If first <li> has an <image> child
if ($first.has('img').length) {
// Move the <li> to second position
$first.insertAfter($first.next())
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><img src="test.img" alt="IMG"></li>
<li><p>text</p></li>
<li><p>text2</p></li>
</ul>
<hr>
<ul>
<li><p>text</p></li>
<li><img src="test.img" alt="IMG"></li>
<li><p>text2</p></li>
</ul>