Add an array to every item on the list using individual unordered lists

I need help with a JavaScript code that will add elements from an array to each list on my webpage. The goal is to add numbers 1 through 4 to the list items, but only up to the number of items in the array. If there are only three list items, I want the script to stop at 3 and not add another item. Additionally, I want to remove any zeros present.

Any assistance would be greatly appreciated!

var levels = [ "1", "2", "3", "4" ];
$('ul li').each(function (x) {
 $(this).append(levels[x]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul>
 <li>0</li>
 <li>0</li>
 <li>0</li>
 <li>0</li>
</ul>

<ul>
 <li>0</li>
 <li>0</li>
 <li>0</li>
</ul>

<ul>
 <li>0</li>
 <li>0</li>
 <li>0</li>
 <li>0</li>
</ul>

FIDDLE

Answer №1

To start, iterate through the lists and then go through each item within the list

var levels = [ "1", "2", "3", "4" ];

$('ul').each(function(i, ul) {
    $(ul).find('li').each(function(j, li) {
        $(this).html(levels[j]);
    });
});

FIDDLE

Answer №2

Utilize the :nth-child() selector along with jQuery.each() method

var levels = ["1", "2", "3", "4"];
$.each(levels, function(i, x) {
  $('ul li:nth-child(' + (i + 1) + ')').html(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul>
  <li>0</li>
  <li>0</li>
  <li>0</li>
  <li>0</li>
</ul>

<ul>
  <li>0</li>
  <li>0</li>
  <li>0</li>
</ul>

<ul>
  <li>0</li>
  <li>0</li>
  <li>0</li>
  <li>0</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

Utilizing the onclick event to call a function with multiple arguments within Template literals

How can I properly write a function with multiple arguments using JavaScript post ES6 template literals when called by an onclick event? Here is my code: function displayImg(imageUrl, gameName, gameSummary, gameYear, cardId) { cardId = cardId.toStrin ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

"Encountering a RangeError with Node.js Sequelize while working with

I need some assistance with using Sequelize in my Node.js application paired with MySQL. When I try to execute the command npx sequelize db:create, I encounter an error that I do not know how to resolve. Any guidance on this matter would be greatly appreci ...

Adjusting Image Width with jQuery on Hover

I am trying to create a hover effect for two images placed side by side. When the user hovers over one of the images, it should expand. HTML: <a href="#"><div id="skinny"></div></a> <a href="#"><div id="room9"></div ...

Is it possible to open a PDF file in a new tab using Angular 4?

When attempting to open a PDF file using the window.open() function, I encountered an issue where the window would open and close automatically, causing the file to be downloaded rather than displayed in a new tab. Despite not having any ad blockers inst ...

Looking to retrieve the mouse coordinates using JavaScript

How can I use JavaScript to track the mouse position on a canvas? Upon visiting this page: http://billmill.org/static/canvastutorial/mouse.html They provide this code snippet: function initializeMouse() { canvasMinimumX = $("#canvas").offset().left; ...

Transferring PHP array data to JavaScript without being exposed in the source code

In the process of creating a historical database, I am currently handling over 2,000 photos that require categorization, out of which approximately 250 have already been uploaded. To efficiently store this data, I have set up a MySQL database with 26 field ...

What are the steps to retrieve all memcached information using node.js?

One of my main objectives is to have the user session data expire when they close their browser. However, I am facing a challenge because my Server depends on memcached to function correctly. Therefore, I need to find a way to specifically delete the use ...

Error: The property 'updateOne' cannot be read because it is undefined

I have been struggling to update an array in my MongoDB database, despite following the steps outlined in the official documentation. I can't seem to make it work. Can anyone provide assistance? I went through the official documentation, but unfortun ...

"Resolving the Problem of a CSS Width Setting at 100

Encountering difficulties when using 100% in the container CSS. Referencing the attached image, you can see the RED background color displayed on the right side image. Below is the link to my CSS code on jsfiddle. Please review it and advise on the modifi ...

Tips for retrieving user input from an HTML form and using it to make an Axios POST request

I am facing an issue with sending a post request to my API using axios. A user enters an email and password in a html form, but when the request is sent, the body of the request appears to be empty based on the chrome dev tools. I am struggling to extract ...

Transforming JQuery Output into an HTML Table Layout

Hello there! I am currently working on parsing an XML file within my web page using jQuery. Here is a snippet of the code: function loadCards(lang) { $.ajax({ type: "GET", url: 'data.xml', dataType: "xml", suc ...

Highlight.js is not able to display HTML code

It's strange, I can't seem to get the HTML code to display correctly. This is my HTML: <head> <link rel="stylesheet" href="/path/to/default.css"> <script src="/path/to/highlight.pack.js"></script> <script& ...

Decoding a JSON object in node.js

{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d6ded2c3dfd682f3d4ded2dadf9dd0dcde">[email protected]</a>","last_login":"11:25:24 AM","name ...

Animate a DIV's width to zero, including any padding

I am a beginner when it comes to jQuery and CSS, and I am attempting to animate two DIVs with the class .iDoElement using the following JQuery code: $( '.iDoElement' ).each(function () { var randomDelay = Math.floor(Math.random() * 600); ...

Retrieving information from Laravel route using React

In my Laravel application utilizing Laravel Framework 8.83.16, I have implemented the following function: public function checkIdentifier($physicalItem_identifier) { try { $con = "mysql"; $res = DB::connec ...

Top-notch tools and guides for front-end web development

As I prepare to transition to a new role focused on front-end web development, specifically CSS and jQuery, I am seeking recommendations for valuable resources to enhance my skills in these areas. Whether it be books, websites, blogs, or any other medium, ...

Struggling to apply size in percentage to several images used as a background

Displaying two background images with different positioning: html { background: top left no-repeat url(http://wallpapers.pupazzo.org/animals/Peek-a-Boo_Red_Fox_Kit.jpg), top right no-repeat url(http://www.dcwild.com/images/Fox-Kit-Rive ...

Styling the Bootstrap Side Navigation Bar for Desktop View

My bootstrap navbar has a unique feature where the menu slides out from the right when clicked on mobile and small viewports. However, I want it to display the standard bootstrap styles for the desktop version (no menu button, just inline menu items in t ...

What is the significance of an HTML form entry containing "action='something'"?

While reviewing a HTML file, I stumbled upon the following entry: '<form action="?" ... ' Despite my efforts to decipher its purpose, I am unable to comprehend it. I attempted to search for answers on Google, but unfortunately, no relevant r ...