0

I am attempting to write some jQuery for a simple task, it's not my strong point - what I want it to do is search through a specified div based on it's class, select the images in order and then attach them to a list-item. Problem I am having is that when I append them to the List item each of the image will have a set li with a class for example .first-li will have the first image appended to it), they do it in a random order resulting in the incorrect order.

It's more than likely the way I am appending the images but I seem to be at a loss

$(document).ready(function() {
  $('.content-home').ready(function() {
    $(this).find('img:nth-child(1)').appendTo('.first-li');
    $(this).find('img:nth-child(2)').appendTo('.second-li');
    $(this).find('img:nth-child(3)').appendTo('.third-li');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="content-home">
        <h4>Content</h4>
        <img src="C:\Users\CyberfrogPC2\Desktop\devstuff\MerseyTest\1.jpg" />
        <img src="C:\Users\CyberfrogPC2\Desktop\devstuff\MerseyTest\2.png" />
        <img src="C:\Users\CyberfrogPC2\Desktop\devstuff\MerseyTest\3.png" />
        <ul>
          <li class="first-li"></li>
          <li class="second-li"></li>
          <li class="third-li"></li>
        </ul>
      </div>

I have three images for testing purposes, each with a number from 1 - 3 on them so I can see the order when they are appending, in some cases 2 and 3 may end up on the same line, or one will be on the last li whilst the number 3 isn't appended at all.

Any help would be appreciated.

BenJ30
  • 86
  • 1
  • 8
  • Following your code...I give some id to your images..https://jsfiddle.net/4u46aqsj/ Regards – Albeis Jun 13 '17 at 10:02

1 Answers1

1

After first .appendTo(), DOM reflow takes place, so img:nth-child(3) doesn't refers to same DOM element.

You can use combination of .each() and its index to target the desired li, then .appendTo() can be used.

$(document).ready(function() {
  $('.content-home img').each(function(index) {
    $(this).appendTo($('.content-home li').eq(index));    
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-home">
  <h4>Content</h4>
  <img src="C:\Users\CyberfrogPC2\Desktop\devstuff\MerseyTest\1.jpg" />
  <img src="C:\Users\CyberfrogPC2\Desktop\devstuff\MerseyTest\2.png" />
  <img src="C:\Users\CyberfrogPC2\Desktop\devstuff\MerseyTest\3.png" />
  <ul>
    <li class="first-li"></li>
    <li class="second-li"></li>
    <li class="third-li"></li>
  </ul>
</div>
Satpal
  • 132,252
  • 13
  • 159
  • 168