add items to the dropdown using a loop

I am encountering an issue with my bootstrap dropdown. I am trying to loop a specific number of times and append each loop number inside a li. However, my current code is not working as expected. Can anyone provide guidance on how to fix this? Thank you in advance.

for (var i = 0; i < 5; i++) {
  console.log(i)
  $('.dropdown-menu ul').append(`<li><a class="dropdown-item">test ${i}</a></li>`)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>

<div class="dropdown">
  <button class="btn btn-secondary w-100 d-flex justify-content-between align-items-center" type="button" data-bs-toggle="dropdown">test</button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
  </ul>
</div>

Answer №1

The selector for the ul is not accurate. The correct format should be ul.dropdown-menu

.dropdown-menu ul looks for a ul element within any element with the class dropdown-menu.

ul.dropdown-menu finds a ul element specifically with the class dropdown-menu, which is the intended target.

You can test it by using the snippet below.

<script>
    let ul = $('ul.dropdown-menu');
    console.log(ul);
    for (var i = 0; i < 22; i++) {
        console.log(i);
        let li = $(`<li><a class="dropdown-item">test ${i}</a></li>`);
        ul.append(li);
    }
</script>

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

Issue with Electron and Node.js: Application fails to launch due to inability to locate the app within the modules

I am currently testing out an electron application that is supposed to link to our website. I decided to follow one of the tutorials available. Unfortunately, upon launching the app, I encountered the following error: Error log : akshay@akshay-mint-deskt ...

Accessing node postgres and fetching combined fields with duplicate names

Currently, I am developing a node.js application that utilizes the pg package to connect to a PostgreSQL database. The problem I am encountering involves querying data using a join statement and finding that fields from one table overwrite those from anoth ...

VueX Error: The store property is undefined and cannot be read

In my vue.js store, I am able to access the state parameters within the computed section of a component: computed: { BASE_URL () { return this.$store.state.BASE_URL; } However, when attempting to access the store in the methods of the same co ...

Sending a picture through AJAX using the camera feature of p5.js

Currently, I am exploring the camera functionality of p5.js to capture video. However, I am facing a challenge when trying to upload these images to a server using ajax. I am unsure about how to convert a p5.js Image object into a suitable format for trans ...

Unable to make a successful POST request using the JQuery $.ajax() function

I am currently working with the following HTML code: <select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select> along with an: <input type="text" id="prd_price" ...

Having trouble with the placeholder blur feature on images in Next.js?

Within my website, I have a dynamic route set up as /titles/[slug].js. Upon initially navigating to this route, everything functions as expected - the placeholder blur effect displays on all images and animations triggered by react-intersection-observer wo ...

Discovering the wonders of React and Javascript through the powerful Map function

I've exhausted all my knowledge of map functions and syntax, but I keep encountering the error TypeError: Cannot read property 'action' of undefined. This issue seems to stem from this line: constructor(data=[]). Typically, I am only familia ...

The baffling quirks of variables within a Jquery loop

Unfortunately, I'm struggling to come up with a more fitting title for my question, but I'll do my best to provide a clear explanation of my issue. Here is the code snippet I am working with: let pdfInvoice_sub_template = [ {text: '{ ...

Toggle the div if the if statement is true; otherwise, hide the broken

click: function(event, data) { $('#clicked-state') .text('You clicked: '+data.name); if (data.name == "VA") { $('#va').toggle(); } else { $('#va').style.d ...

Is there a way to track and detect alterations to an element using JavaScript or jQuery

Can I detect the addition of a specific CSS class to an element without having to create a new event? ...

Ways to dismiss a Modal popup instantly without having to wait for an ajax response

I am currently facing an issue with sending email attachments through ajax. The process takes too long to send and close the email modal window. I am looking for a solution where the modal window closes immediately after clicking the send email button, all ...

Designing a dynamic patterned backdrop that seamlessly extends for a column in bootstrap

Experiencing some difficulties with Bootstrap and creating a resizable column background. In one row, there is a column with a fluid image at the top, another column below it with a CSS class that gives it a repeating background along the Y axis, and fina ...

Transform JSON headers and rows into Object keys using Node.js

I am currently working on retrieving data from an API in JSON format using Node JS. The JSON data consists of headers and rows, including information such as "Vendor, Price, SKU, Error" (see the attached screenshot). I am looking to structure this data int ...

Creating a list in React and adding a delay using setTimeout() method

I'm a beginner when it comes to working with React and I've been attempting to display a list of posts using a JSON array. My goal is to have the list render after a certain number of seconds, but for some reason, the list isn't rendering us ...

Effortless method to share an image and leave a comment on a user's Facebook wall using the

I am trying to efficiently share an image and comment from my website to a Facebook user's own wall. Despite searching through multiple resources and Facebook API documentation, I am struggling to find a simple solution for this basic task. Facebook ...

ThreeJS | The object's position cannot be cloned as it seems to be undefined, however, this is unexpected

My code problem is not as complex as it seems. The issue lies within the section marked by the "ERROR APPEARS HERE" comments. The error message I am encountering reads: Uncaught TypeError: Cannot read property 'position' of undefined This er ...

Using Ajax to Receive Data in a Separate JavaScript Function

I have a scenario where I am making an AJAX call in one function and attempting to capture the result in another function. Let me explain this in detail below: function myMain(){ var test = myWPackage(); alert(test); } function myWPackage(){ ...

Is it necessary to specify the JavaScript version for Firefox? (UPDATE: How can I enable `let` in FF version 44 and below)

Our recent deployment of JavaScript includes the use of the let statement. This feature is not supported in Firefox browsers prior to version 44, unless JavaScript1.7 or JavaScript1.8 is explicitly declared. I am concerned about the potential risks of usi ...

My code is designed to operate exclusively on the initial element containing an ID

Check out this screenshot to see what I'm aiming for. I discovered a solution online that might help me achieve my goal. To test the solution, I set up a simple HTML structure like this: <div id="block"> <img id="img& ...

JavaScript can dynamically attach EventListeners to elements, allowing for versatile and customized event

I am currently populating a table using data from an XML file. One of the columns in the table contains links to more details. Due to the unique requirements of my web page setup (Chrome extension), I need to dynamically add an event handler when the table ...