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 >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/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<div >
<button type="button" data-bs-toggle="dropdown">test</button>
<ul aria-labelledby="dropdownMenuButton1">
</ul>
</div>
CodePudding user response:
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 >test ${i}</a></li>`);
ul.append(li);
}
</script>