简体   繁体   中英

How to trigger event when 5 list <li> items have been added to my dynamically generated <ul> list?

I have a list in html (like a to-do list) and I want a button to appear when the user adds 5 items to that list.

I wrote this in js but it is not working:

function addButton(){
const glist = document.querySelectorAll('.gratitude_container > ul > li')
const gratListArray = Array.from(glist);
if (gratListArray === 4) {
    FortuneButton.classList.remove('hidden')

}

my html is:

    <form>
        <input type="text" placeholder="Enter it here..." class="gratitude_input" />
        <button class="gratitude_button" type="submit">
            <i class="fas fa-plus-circle"></i>
        </button>
    </form>
    </div>
   

    <div class="gratitude_container">
        <ul class="gratitude_list"></ul>
    </div>

</div>

Any ideas?

Can you recreate this issue in a demo on code pen? Looking at the code you provided, the JS should never hit, since you don't have any li's in your ul. But that might just be what you pasted.

If you can make a demo w/ this same issue, it will be easier to help you out.

probably you should use gratListArray.length in your IF statement.

enter code here

 function showButton() { const list = document.getElementsByClassName("gratitude_list")[0]; let items = list.getElementsByTagName("li"); const button = document.getElementById("newButton"); if (items.length >= 5) { button.style.display = "block"; } else { button.style.display = "none"; } } showButton();
 <div class="gratitude_container"> <ul class="gratitude_list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> <button id="newButton">Button</button> </div>

Assuming you're getting your array as expected, my solution would be to add an event listener to your function.

Based on the code you shared I dont see what is triggering your current function. all functions need to be declared by an event eg. page load, timer, or user interaction... to name a few. With an event listener each time there is a click the array is updated and the if statement is tested.

document.querySelector("button").addEventListener("click", () => {
    const glist = document.querySelectorAll('.gratitude_container > ul > li')
    const gratListArray = Array.from(glist);
    if (gratListArray.length === 4) {
    FortuneButton.classList.remove('hidden')
})

hope that helped and have fun coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM