Having trouble with Append() function not functioning properly within the if statement nested inside a .each loop in jQuery

Looking to add text after the 4th element in a ul li? I tried using the append function, but it's appending before every li element. Here's the HTML:

<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 I used:

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

Any suggestions on how to achieve this without appending before every li element?

Answer №1

If you are aiming to target the fourth item specifically, you can achieve this without a loop. Utilize the :eq() selector to directly pinpoint the fourth element with an index of 3. Give the following code a try:

$('.gallery li:eq(3) a').append(' <span>Click Here</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>

Answer №2

If you want to add content to a specific list item while looping through them, you can do so by targeting the current iteration:

$('.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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjustable centralized menu with buttons that resize accordingly

I am currently working on making a webpage responsive. I have successfully created a logo div that resizes accordingly. Now, I am facing a challenge with centering the buttons in the menu list. Despite my efforts, the buttons are not aligning in the center ...

Tips for updating the color of carousel image slider indicators (arrows) specifically for the second slide

Is there a way to customize the carousel image slider indicator arrows for only the second image slide? For the first slide, I want the indicators to be black, but for the second slide, I would like them to be white. Can this be achieved? I attempted to ...

Tips for efficiently handling large Excel files in NodeJS without freezing the user interface

Currently, my NodeJS/Angular/Electron app is utilizing the ExcelJS library to read large Excel files that contain over 10,000 lines. While smaller files are processed smoothly, larger files take between 3.9 and 5 seconds to load, during which time the CSS ...

Split the output into two separate columns in a cshtml file using a foreach

Is there a way to modify my current code so that the output is displayed in two columns instead of one? Would using flex grid be the best approach, or is there another method I should consider? <div class="col-12 box-container"> <div class=" ...

Disable browser suggestions in Material UI's Autocomplete component

Encountering an issue with Material-ui Autocomplete: import Autocomplete from "@material-ui/lab/Autocomplete"; Currently using it in: <Autocomplete id="checkboxes-tags-demo" autoComplete={false} options={sta ...

What is the best way to store multiple forms in a single request using React?

Is there a more efficient way for me to save multiple forms in multiple child components from the parent component using just one API request? I have attempted to utilize Context and reducer, which did work. However, I am unsure if this is the best approa ...

Styling is lost in FancyBox popup when loading Partial View

I've been attempting to incorporate a partial view into my MVC project using fancybox. It seems to be loading the content correctly, mostly anyway, as it tends to cut off part of the page and loses all styling from the view upon loading. Even after i ...

Exploring The Depths of HOC with Enzyme and TypeScript

I have a higher-order component (HOC) that I need to test. During shallow mounting, I need to call some class methods: it('Should not call dispatch', () => { const dispatch = jest.fn() const WrappedComponent = someHoc(DummyComp ...

Change the function from onLoad to onClick exclusively

I'm experiencing a particle explosion on my webpage due to this code. I connected the onClick function to a button in my HTML so it executes only when that specific button is clicked. However, the function automatically runs when I load the HTML and ...

What could be the reason for ThemeProvider (Material UI) failing to function properly in this scenario?

I've encountered something puzzling with Material UI. Despite my experience with it, I can't seem to figure out why my H2 tag in the nested component is rendering in Times instead of Arial. I've double-checked the docs and my code, but the i ...

The power trio: Form, AJAX, and PHP

I am encountering an issue with my Subscribe form where the email address is not getting inserted into the MySQL db despite successfully creating a date and time record using AJAX. Can anyone identify what might be causing this problem? Here is the code i ...

Header Logo centered at the top

I am using a Bootstrap 4 navbar where the nav-brand is centered on a computer window, but shifts to a dropdown when expanded on mobile. Is there a way to keep the brand fixed at the top and center? Here is my navbar code in HTML: <nav class="navba ...

Safari browser is experiencing issues with the custom file upload script

My custom upload script allows users to easily select images for upload by clicking or dragging them into the designated box. A preview of the chosen image should appear, and this functionality works smoothly in Firefox and Chrome. However, I've encou ...

When invoking a JavaScript method, the context variable 'this' is lost

I have developed a basic pointer to a method like this: export class SmbwaService { getExistingArsByLab(labId: number): Observable<SmwbaAr[]> { this.otherMethod(); } otherMethod(): void { } } let method: (x: number) => ...

Ajax: setInterval function successfully runs code but does not refresh the HTML output

I have multiple div elements in my code. I want to update the HTML content inside them based on an API request. The updating process works fine, but the HTML content doesn't refresh visually (meaning that even if I receive a new result from the API, t ...

What is the best way to align this form in the middle of a Jumbotron with Bootstrap 4?

<!DOCTYPE html> <head> <title>Destiny 2 App</title> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shri ...

Having issues executing a conditional check using ng-if in AngularJS

I am attempting to verify a condition and here is how it appears: <ons-list-item ng-repeat="EventList in EventLists" ng-if="EventList.start.dateTime | DateMonth == TodayDetail"> I am encountering difficulties with this ng-if="EventList.start.dateTi ...

Disregard any unnecessary lines when it comes to linting and formatting in VSC using EsLint and Prettier

some.JS.Code; //ignore this line from linting etc. ##Software will do some stuff here, but for JS it's an Error## hereGoesJs(); Is there a way to prevent a specific line from being considered during linting and formatting in Visual Studio Code? I h ...

What is the best way to design distinct buttons for various devices?

For my current responsive web design project, I have utilized Bootstrap extensively. Recently, I encountered a new issue that I'm uncertain of how to tackle. The problem arises with the following HTML code snippet: <!-- button color depending on d ...

Display a single image on the tablet and a distinct image on the computer

Currently, I am encountering an issue with my webpage located at . The problem lies in the right upper corner where a ribbon is located. However, when viewing the page on a tablet, the ribbon overlaps with my menu. To resolve this, I thought about displa ...