Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
In this part of a function, I want to add click listener to the switch checkbox.. How can I do that from the innerHTML?!?

    const card = document.createElement('div');
    card.innerHTML = `
    <div class="card">
            <div class="switch">
                <label id="check">
                     <input type="checkbox">

                </label>
                <span>Captured</span>
            </div>
    </div>
`;


What I have tried:

I tried to access the div from document.getElementByID() but it says:
can't read property addeventlistener of null
Posted
Updated 2-Jul-21 5:40am
Comments
SeeSharp2 2-Jul-21 10:16am    
Add an id to your div.
light93 2-Jul-21 10:57am    
I get: Cannot read property 'id' of null
SeeSharp2 2-Jul-21 11:10am    
That's because whatever you typed into getElementByID does not exist. Put an id on your checkbox, isn't that what you want to have do something when clicked/checked?

1 solution

As DevParty mentioned, you need to give your <input> element an id="" attribute to help identify it within the page. Alternatively you can give it a name="" attribute and use getElementsByName() which returns an array.

The other important factor is to make sure you actually append the new element to the document before attempting to attach an event listener. Using document.createElement() creates it but it is currently detached from the DOM, so I don't believe you can bind an event until it's in the DOM and interactable.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900