What is the best way to target an element that does not exist yet?

I have a project for managing a todo list. When I click an "add" button, it creates a div element with another "add" button inside it. That part is easy. But now, I want to select that inner button so that I can use it to add a text input form inside the newly created div.

I suspect that the reason it's not working is because the element doesn't exist at the time of selection.

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 symbol. Upon clicking the plus icon in the newly created div, I want a text input form to appear. Any assistance on this matter will be highly appreciated!

Answer №1

It is true that querySelector will return null if the specified element does not yet exist.

In this scenario, you have the option to add the event listener immediately after creating 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 in this manner
    addListItem.className = 'addListItem';
    addListItem.innerHTML = '<i class="fas fa-plus fa-2x"></i>'
    todoDiv.appendChild(addListItem);
    document.body.appendChild(todoDiv);
    // Now that we have the element, add the event listener:
    addListItem.addEventListener('click', () => { 
        let inputBox = document.createElement('input');
        inputBox.setAttribute('type', 'text');
        todoDiv.appendChild(inputBox);
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Component template using Knockout.js and RequireJS for HTML widgets

Trying to implement the widget example for knockout from here. Unfortunately, I am having issues loading the template from an external HTML file using requirejs. ko.components.register('like-or-dislike', { template: { require: &apos ...

I am interested in extracting information from the Firebase real-time database and showcasing it on my HTML webpage

I am struggling to display data from the Firebase real-time database on my HTML page. Even though I can see all the data perfectly in the console, it doesn't show up on the webpage. I attempted to use a for loop, but it still doesn't display the ...

Messages traced by log4javascript are not being displayed

I am currently utilizing log4javascript version 1.4.3. Everything in my application seems to be functioning correctly with all log levels except for trace. To simplify the troubleshooting process and ensure that the issue does not lie within my applicati ...

Issue with integrating Google Spreadsheet as the data source for a Next.JS website: updates are not reflecting on the website pages

The website for this restaurant was created by me, using Google Spreadsheet to populate the menu pages. I chose this method for its simplicity and familiarity to the client. I'm utilizing the google-spreadsheet package to extract necessary informatio ...

What is the best way to compress all folders, including the main directory?

I am working on a PHP script where I need to zip all directories, including the root directory. For instance, if my script file is located at /practice/zip/index.php, and I want to create a zip archive for the entire /practice directory. Currently, my sc ...

When testing my jQuery locally, it runs smoothly. However, upon uploading it to my website, I encounter some issues where it

After successfully running my webpage on localhost, I encountered an issue when uploading it to my website. Only a portion of the code seems to be executing properly. I have included the following jquery function in my script and there are no reported err ...

Transfer the output to the second `then` callback of a $q promise

Here is a straightforward code snippet for you to consider: function colorPromise() { return $q.when({data:['blue', 'green']}) } function getColors() { return colorPromise().then(function(res) { console.log('getColors&ap ...

CSS Flexibility

Greetings everyone, it's been a while since I dabbled in web development. I recently worked on my site with the intention of making it responsive using flexbox. This is my first time posting here, so please guide me on how to seek help more effective ...

The issue persists as the Ajax request continues to return false

I have created a verification program using an ajax request: $("#codeSbmt").click(function(){ var $input = $("#fourDigit"); codeCheck("codeTest.php?q=" + $input); }) function codeCheck(url) { var xh ...

The behavior of Date's constructor differs when applied to trimmed versus untrimmed strings

Although it's commonly advised against creating a date from a string, I stumbled upon an interesting phenomenon: adding a space before or after the date string can impact the resulting date value. console.log([ new Date('2019-03'), ...

Angular material table cell coloring

Here is my current setup: I have an array of objects like this: users : User []; average = 5; compareValue (value){ ...} And I am displaying a table as shown below: <table mat-table [dataSource]="users"> <ng-container matColumnDef= ...

Is there a way to remove CSS based on the generated HTML code?

Currently tackling a project in Next.js involving custom SCSS, Bootstrap SCSS, and React-Bootstrap. Struggling with the bloated size of our main.scss file due to unused CSS. After observing that 95% of the CSS is not utilized, I aim to eliminate all unnec ...

Calculate the difference in days between two selected dates from an Ajax Datetime Picker using JavaScript

How can I use JavaScript to count the number of days between two selected dates from Ajax date time pickers in my aspx page? The script should automatically input this calculated value into a designated "Number_Of_Days" text box without requiring a page ...

What steps can I take to give priority to a particular ajax call?

Every 10 seconds, two ajax based methods are executed. However, when I submit the form for processing, it waits for the previous ajax calls to complete before processing. I want to prioritize the form submission. Below is the script that I am using: func ...

Navigating through directory paths in JavaScript can be a daunting task for many

In my app.js file, I've included the following code: app.use(multer({dest:'./uploads'})) What does './uploads' refer to here? It is located in the same directory as app.js. In what way does it differ from simply using uploads? I ...

Create a feature in three.js that allows users to click on an object to display information about the

After loading an object using the GLTF loader into my scene, I want to create a point on this object to display popup info. Is there a way to add a point to a specific location on the object? ...

Updating parent data in Vue.js does not automatically trigger an update in the child component

I have the following: Vue.component('times-updated', { template: '<span>Times Updated: {{ timesUpdated }}</span>', data: function() { return { timesUpdated: this.$parent.myData.timesUpdated ...

Tips for dynamically passing a string into a Javascript function

Here is a JavaScript function that I have: function doIt(link) { alert(link); } I am using this function in the following JavaScript code snippet. Here, I am dynamically creating an anchor tag and appending it to my HTML page: jQuery.each(data, func ...

Dealing with Regular Expressions in Javascript and PHP Challenge

I am struggling to achieve the same outcome with my JavaScript as I do with my PHP code. The issue lies in how JavaScript omits backslashes, unlike PHP. To address this, I have included random forward and backward slashes to cater for different systems. Se ...

Setting up user roles using Firebase Auth in NextJS application

Seeking a solution to implement a multi-level role system for my blog website. Currently utilizing Firebase Auth for authentication with email/password, but all users have the same posting/editing access. Looking to differentiate between Admins, Moderators ...