John R
John R

Reputation: 257

How to add tags depending on the length of another div

I have the following code below. I need to add a <li> tag inside the <ul> of the carousel-controls for each image, since the number of images can vary, I need to do it with js, but not sure what to do after I get the length of image-controller

var img_number = $(".image-container img").length;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='image-container'>
  <img src="/img.png" alt="xga-1">
  <img src="/img2.png" alt="xga-1">
  <img src="/img3.png" alt="xga-1">
</div>

<div class="carousel-controls">
   <p class="angle-left" data-icon='ei-chevron-left' data-size='m'></p>
   <ul>
      <!-- Insert a <li>  for each image -->
    </ul>
   <p class="angle-right" data-icon='ei-chevron-right' data-size='m'></p>
 </div>

Upvotes: 1

Views: 69

Answers (2)

FatehiAbdoThabit
FatehiAbdoThabit

Reputation: 590

Like this you can add them

$(".image-container img").each(function(){
$("ul").append("<li>"+$(this).html()+"</li>")
}
);

Upvotes: 0

Dekel
Dekel

Reputation: 62636

You don't really need to do anything with the length of the images you found, you can just loop over them and append them to the UL element, wrapped with a new li element:

$(function() {
  $(".image-container img").each((i, el) => {
    $('ul').append($("<li>").append(el));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='image-container'>
  <img src="/img.png" alt="xga-1">
  <img src="/img2.png" alt="xga-1">
  <img src="/img3.png" alt="xga-1">
</div>

<div class="carousel-controls">
   <p class="angle-left" data-icon='ei-chevron-left' data-size='m'></p>
   <ul>
      <!-- Insert a <li>  for each image -->
    </ul>
   <p class="angle-right" data-icon='ei-chevron-right' data-size='m'></p>
 </div>

Upvotes: 1

Related Questions