Search code examples
javascriptkeydowncreateelementqueryselector

Select tags created by createElement JS


I create tags when we keydown enter in the input and i would like to select the checkbox and apply an event change. So how can i select the tags created by createElement?

HTML

<div class="container">
        <div class="row">
            <div class="col-4">
                <div class="container-list">
                    <h1>To Do List</h1>
                    <input type="text" placeholder="Ajouter une tache">

                </div>
            </div>
        </div>

    </div>

JS

const list = document.querySelector('.container-list');
const input = document.querySelector('input');
// const icons = document.querySelectorAll('i');
const listIcons = document.querySelectorAll('.list input[type=checkbox]');

input.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
        const listAdded = document.createElement('div');
        listAdded.innerHTML = "<input type='checkbox'>" + '<span id="listContent">' + input.value + '</span>' + '<i class="fas fa-edit"></i>' + '<i class="fas fa-trash"></i>';
        listAdded.setAttribute('class', 'list');
        list.appendChild(listAdded);
    };
});

console.log(listIcons)

listIcons.forEach(listIcon => {
    listIcon.addEventListener('change', () => {
        alert('test')
    });
});

Solution

  • A reference to your element gets stored in the variable itself when you call document.createElement. If you wish to use that element in other functions or outside the scope of the function where you create the element, just declare that variable as a global variable.

    In the code you provided, the listAdded variable is exactly what you're looking for.