Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

append to dropdown on loop

I have a bootstrap dropdown what I want is to loop to a certain number and append li with each loop number inside but it is not working. How can I fix it? Thanks 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@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The selector for the ul is incorrect. It should be ul.dropdown-menu

.dropdown-menu ul will try to find a ul element inside any element that has the class dropdown-menu.

ul.dropdown-menu will find a ul element that has dropdown-menu class. This is what you want.

Try the following snippet.

<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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading