skip to Main Content

I’m trying to implement addEventListener so that every time I click a button a new LI will be added to my HTML with text.
For some reason the LI is added for a fraction of a second and then disappears.
I have implemented a form with user input similarly while listening to ‘submit’, but when I try to do the same with ‘click’ it won’t work.
I can use the ‘submit’ option but I’m trying to understand why ‘click’ is not working.
I’d appreciate any help.
Thank you!

const searchBtn = document.querySelector('#searchBtn');
const list = document.querySelector('#uls');

searchBtn.addEventListener('click', function () {
    const movieName = document.createElement('LI');
    const text = "works";
    list.append(movieName);
    movieName.innerHTML = text;  
    }
)

3

Answers


  1. There are some different between click event and submit event. For example the submit() method waits for the DOM to load, but the click() method doesn’t. I recommend you to study about it.

    Login or Signup to reply.
  2. <html>
    
    <head>
    
    </head>
    
    <body>
        <ul id="uls"></ul>
        <button id="searchBtn">Search</button>
        <script>
            const searchBtn = document.querySelector('#searchBtn');
            const list = document.querySelector('#uls');
    
            searchBtn.addEventListener('click', function () {
                const movieName = document.createElement('LI');
                const text = "works";
                list.append(movieName);
                movieName.innerHTML = text;
            }
            )
        </script>
    </body>
    </html>

    I tried the following code, exactly as your code, it seems to be working perfectly.
    Perhaps your page is being reset whenever you are clicking the button, which will reset and re-render your page. May be you need to look into it

    Login or Signup to reply.
  3. Try including the attribute type="button" on the button element declaration in HTML.

     <button id="searchBtn" type="button">Search</button>
    

    This prevents the button submitting the form (which resets the page), because the default button type is "submit".

    If you never want the form to be submitted, try removing the opening and closing form tags, or supply a submit event handler that calls event.stopPropagation and/or event.preventDefault.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search