What is the best way to iterate through my array and display each value within my button element?

I have a challenge where I'm trying to iterate over an array named topics. This array contains the names of various people. Within my loop, my goal is to extract each name and insert it into a button as text.

When I use console.log within my loop, I can see each name from the array being printed. However, when I attempt to append the text to my buttons, only the last name in the array is added.


var topics = ["Lebron James", "Kevin Durant", "Steph Curry", "James Harden", "Russel Westbrook", "Giannis Antetokounmpo", "Kawhi Leonard", "Anthony Davis", "Paul George", "Kyrie Irving"];

for (var i = 0; i < topics.length; i++) {
    $(".gifnames").append("<button type=\"button\" class=\"btn btn-primary\">");
    $("button").text(topics[i]);
    console.log(topics[i]);
}

The issue I'm facing is that only Kyrie Irving's name is being added to all buttons instead of having each name added to the respective buttons created.

Answer №1

$("button") selects all the buttons on the page. Consequently, in each loop iteration, it updates the text of every button with the current item. This means that in the last iteration, all buttons will display the text of the final item in the array.

To target a specific button, you can utilize jQuery's .eq() method as shown below:

var topics = ["Lebron James", "Kevin Durant", "Steph Curry", "James Harden", "Russel Westbrook", "Giannis Antetokounmpo", "Kawhi leonard", "Anthony Davis", "Paul George", "Kyrie Irving"];

for (var i = 0; i < topics.length; i++) {
  $(".gifnames").append("<button type=\"button\" class=\"btn btn-primary\">");
  $("button:eq(" + i + ")").text(topics[i]);
  console.log(topics[i]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gifnames"></div>

Answer №2

When you include the following line within your loop, it updates the text on all buttons:

$("button").text(topics[i]);

Since the selector used will target every buttons tag in the document, the last iteration of the loop assigns the final array text to all buttons. One way to resolve this issue is by first creating the button, setting the associated text, and then appending it to the container:

var topics = ["Lebron James", "Kevin Durant", "Steph Curry", "James Harden", "Russel Westbrook", "Giannis Antetokounmpo", "Kawhi leonard", "Anthony Davis", "Paul George", "Kyrie Irving"];

for (var i = 0; i < topics.length; i++)
{
    $('<button type="button" class="btn btn-primary">')
        .text(topics[i])
        .appendTo(".gifnames");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gifnames"></div>

Answer №3

Imagine making this change instead?

for (let index = 0; index < topics.length; index++) {
    let element = "<button type='button' class='btn btn-primary'>"+topics[index]+"</button>";
    $(".gifnames").append(element);
    //$("button").text(topics[index]);
    console.log(topics[index]);
  }

Answer №4

To make it easier to select each button, you can assign a unique attribute to each one.

var topics = ["Lebron James", "Kevin Durant", "Steph Curry", "James Harden", "Russel Westbrook", "Giannis Antetokounmpo", "Kawhi leonard", "Anthony Davis", "Paul George", "Kyrie Irving"];

for (var i = 0; i < topics.length; i++) {
 $(".gifnames").append("<button type=\"button\" data-id=\""+topics[i]+"\" class=\"btn btn-primary\">");
  $("button[data-id=\""+topics[i]+"\"]").text(topics[i]);
  console.log(topics[i]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gifnames"></div>

Answer №5

Check out this simple way to achieve it using vanilla JS.

var topics = ["Lebron James", "Kevin Durant", "Steph Curry", "James Harden", "Russel Westbrook", "Giannis Antetokounmpo", "Kawhi Leonard", "Anthony Davis", "Paul George", "Kyrie Irving"];
var gifnames = document.getElementsByClassName("gifnames")[0];

for (var i = 0; i < topics.length; i++) {
  var b = document.createElement("button");
  b.classList.add("btn", "btn-primary");
  b.name = topics[i];
  b.innerHTML = topics[i];
  gifnames.appendChild(b);
}
.btn-primary {
  background-color: aliceblue
}
.btn {
  display: block
}
<div class="gifnames">
</div>

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

Stopping errors are a common occurrence in synchronous AJAX

I recently encountered an issue with my AJAX request setup. In the success callback function, I called a new function to render Google links and made another AJAX call. To address some performance concerns, I attempted to change these asynchronous calls t ...

Create a feature that allows users to search as they navigate the map using Leaflet

Exploring the idea of incorporating a dynamic "Search as I move the map" feature similar to Airbnb using Leaflet. Striving to strike a balance between loading data relevant to the displayed portion of the map and minimizing unnecessary API requests trigger ...

Retrieving date from timestamp in a node.js environment

Can someone help me figure out how to display my timestamp as the date in the front end? I've tried multiple methods without success. Here is the code snippet: formulaire.addEventListener('submit', posteValidation); /** * Function to add a ...

Trigger Vue method when the size of a div element changes

Is there a way to trigger a method every time the dimensions (width or height) of a div element change? <template> <div> </div> </template> <script> export default { methods: { updateSize() { // ...

Display data in a template upon receiving a response from the server

Hello, I am currently in the process of developing my very first Angular application and could use some assistance. Specifically, I am working on a component that serves as an image search box. When a user inputs a search query, a request is sent to an API ...

obtain the text content from HTML response in Node.js

In my current situation, I am facing a challenge in extracting the values from the given HTML text and storing them in separate variables. I have experimented with Cheerio library, but unfortunately, it did not yield the desired results. The provided HTML ...

Retrieve the content from a textarea and insert it into a different textarea with additional text included

Users can input HTML codes into a textarea named txtar1. A 'generate' button is available; Upon clicking the 'generate' button, the content of txtar1 will be transfered to another textarea named txtar2 with additional CSS code. Here&ap ...

"Multiple instances of JavaScript files seem to be present when using Ajax navigation

Having some difficulties with AJAX navigation. The issue is that the JavaScript files loaded remain in the browser even after the new content is loaded, even when they are no longer in the DOM. These files appear as VM files in the browser console and cont ...

Clicking on multiple instances of the same Vue.js component (popover) results in displaying identical data

Attempting to display an AJAX response in a popover shown by clicking an icon (a custom Vue component) brings about a challenge. The issue arises when there are multiple instances of this component, dynamically rendered through the v-for directive within a ...

Access Flask variable in JavaScript code

Currently working on a CTF challenge, my query is not seeking assistance in solving it, but rather pertains to syntax. The task involves retrieving the secret key from Flask server's configuration. This key is stored within the app.secret_key variable ...

Tips for customizing babel's preset plugin configurations

I've integrated babel-preset-react-app into my project with the following .babelrc configuration: { "presets": ["react-app"], "plugins": [ "transform-es2015-modules-commonjs", "transform-async-generator-functions" ] } Currently, I&apos ...

What is causing the error message "Uncaught TypeError: Cannot read properties of null (reading 'push')" to be displayed when running this code?

I encountered an issue while trying to run this code which resulted in an Uncaught TypeError: Cannot read properties of null (reading 'push') console.log("HI"); let addbtn = document.getElementById("addbtn"); addbtn.addEventLi ...

What is the best way to retrieve the current complete URL in a Next.js/Typescript component?

I'm working on a component and I need to retrieve the current full URL. Here's a simplified version of what I have: /** * Share dropdown component */ export const ShareDropdown: React.FC<{ className: string }> = ({ className, }) => { ...

What are some effective ways to manage repetitive HTML elements like headers and footers in Angular 4?

Within my Angular web project, I find myself using a variety of different headers on multiple pages. Is there a way to streamline this process by coding the header and footer once and having them automatically included in one or more pages? I am looking ...

A step-by-step guide on increasing native Time variables in JavaScript

How can I dynamically and repetitively add time (both hours and minutes) in JavaScript to effectively increment a date object? There are times when I need to add minutes, or hours, or a combination of both - and I want the resulting total time to be return ...

Unable to access content from a dictionary in Django templates

Currently, I am attempting to retrieve the value of the class method that returns a dictionary. The function is structured as follows: class GetData: def __init__(self, api_key, ip, interface): self.api_key = api_key self.asa_ip = ip ...

Intensive analysis of objects comparing their characteristics

Currently delving into the world of Javascript, I encountered a coding exercise involving a "deepEqual" function that I attempted to write but ultimately struggled with. Even after reviewing the solution, one particular part perplexed me - the for loop, ...

Using Router.back in Next.js triggers a complete page refresh

I am working on a page called pages/conversations/[id].tsx, and here is the code: import Router, { useRouter } from 'next/router' export default function ConversationPage() { const router = useRouter() ... return ( <View ...

Difficulty with two-dimensional arrays in Angular and Typescript

I am currently stuck trying to assign values to a 2-dimensional object array in Angular/Typescript. I have noticed that the last assignment seems to override the previous ones, but I cannot pinpoint why this is happening. Could someone please review my cod ...

How can I use jQuery to either display or hide the "#" value in a URL?

I have a question that I need help with. Let's say I have the following links: <a href="#test1"> Test </a> <a href="#test2"> Test 2 </a> When I click on Test, the URL will change to something like siteurl/#test1. However, whe ...