简体   繁体   中英

How do I select an element that hasn't been created yet?

Meaning I have a todo list project where click an add button that creates a div element with another add button inside. Easy enough. Now I want to select that button so that I can use it to add a text input form inside the newly created div element.

I'm assuming the reason it's not creating is because when I select the element it doesn't exist at the time?

const addButton = document.querySelector('.addButton');
const addListItem = document.querySelector('.addListItem');
const todoDiv = document.querySelectorAll('.todoDiv');

addButton.addEventListener('click', () => {
    let div = document.createElement('div');
    div.setAttribute('class', 'todoDiv');
    div.innerHTML = '<a href = "#" class = "addListItem"><i class="fas fa-plus fa-2x"></a>'
    document.body.appendChild(div);
});

addListItem.addEventListener('click', () => {
    let inputBox = document.createElement('input');
    inputBox.setAttribute('type', 'text');
    document.todoDiv.appendChild(inputBox);
});

Here's my HTML as well just in case

<body>
    <div class="sideNav">
        <p class = "heading">&lt;/td&gt;</p>
        <a href = "#" class = "addButton sideButton"><i class="fas fa-plus fa-2x"></i></a>
        <a href="#" class = "sideButton"><i class="fas fa-project-diagram fa-2x"></i></a> 
        <a href="#" class = "sideButton"><i class="fas fa-user fa-2x"></i></a>
        <a href="#" class = "sideButton"><i class="fas fa-cog fa-2x"></i></a>
    </div>



    <script src="script.js"></script>
</body>

The first event will create a div with a plus in it. After clicking the plus in the newly created div I want a text input form to appear. Any help will be greatly appreciated!

Indeed querySelector will return null if the targeted element is not there yet.

But in your case you can just add the event listener right after you create the element:

const addButton = document.querySelector('.addButton');

addButton.addEventListener('click', () => {
    let todoDiv = document.createElement('div');
    todoDiv.className = 'todoDiv';
    let addListItem = document.createElement('a'); // Create the anchor like this
    addListItem.className = 'addListItem';
    addListItem.innerHTML = '<i class="fas fa-plus fa-2x"></i>'
    todoDiv.appendChild(addListItem);
    document.body.appendChild(todoDiv);
    // Add event listener now that we have the element:
    addListItem.addEventListener('click', () => { 
        let inputBox = document.createElement('input');
        inputBox.setAttribute('type', 'text');
        todoDiv.appendChild(inputBox);
    });
});

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