1

I need to append some text after the 4th element inside ul li so I am using the append function for it. The problem is if the statement not working inside .each function and it is appending before every li element.

Here is HTML markup

<ul class="gallery">
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li> 
</ul>

Here is the jquery code

$('.gallery li').each(function( index ) {
        var count = 3;
        if( index == count){
            $( ".gallery li a" ).append('<span>Learn More</span>');
        }
    });

What is the problem is there any other way to achieve this?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Ali Mirza
  • 112
  • 2
  • 9
  • 1
    Why don't you just use `$('.gallery li:eq(3) a').append(...)`? – Barmar May 18 '21 at 18:41
  • 1
    It's obvious what you wanted to do. What's less obvioius is why you thought this would do it? What part of `$(".gallery li a")` says that it should only append to the current item in the loop? – Barmar May 18 '21 at 18:42
  • I don't mean to single you out. There are hundreds of questions like this, it seems to be a common expectation that the selector will only apply within the context of the current loop element. – Barmar May 18 '21 at 18:45
  • I am new to jquery I didn't know well about that – Ali Mirza May 18 '21 at 18:46

2 Answers2

1

You probably only want to append to the list item you're currently iterating on:

$('.gallery li').each(function(index) {
  var count = 3;

  if (index == count) {
    $(this).find('a').append('<span> Learn More</span>');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="gallery">
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
</ul>
isherwood
  • 58,414
  • 16
  • 114
  • 157
1

If your goal is to target the fourth element, then you don't need a loop. You can select it directly using :eq(). Note that the index is zero-based, so the fourth element is index 3. Try this:

$('.gallery li:eq(3) a').append(' <span>Learn More</span>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="gallery">
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
  <li><a href="#">Some Text</a></li>
</ul>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339