Is it possible for JavaScript to interact with elements that are created dynamically?

It's puzzling why the newly generated elements remain unseen by the next function that is called. Any insights on how to address this issue would be greatly appreciated! Resolve: Incorporate async: false to deactivate the asynchronous feature in order to ensure that test-output-2 and test-output-3 are executed after the birth process. By default, ajax operates with async: true, which is comparable to multi-threading.

function birth(mom)
{
    $.ajax(
    {url: "/cgi-bin/count.cgi",   // returns 3 without fail
     async: false,   // include this to disable asynchronous feature and guarantee execution of test-output-2 and test-output-3 post birthing
     success: function(xkids)     // xkids equals 3
     {
         for( var i = 0; i < xkids; i++ )
         {
             mom.appendChild(document.createElement("div"));
             mom.children[i].setAttribute("id", "child-"+i);
         }

         document.getElementById("test-output-1").innerHTML = mom.children.length;   // now there are 3 children
     }
    });
     document.getElementById("test-output-2").innerHTML = mom.children.length;   // no children visible if async: true

} 

var marry = document.getElementById("Marry"); // currently childless
birth(marry);

function whereIsTheChildren()
{
    document.getElementById("test-output-3").innerHTML = marry.children.length;   // no children apparent if async: true
} 
whereIsTheChildren();

Answer №1

Attempting to find a specific element in the DOM before it has been fully loaded will be unsuccessful. This is because the script executes as soon as it is encountered. If the script is placed above the HTML content in the file, the element will not yet exist and therefore cannot be located.

Likewise, sending an AJAX request and assuming that it operates synchronously (waiting for the operation to complete before executing further code) will also not work.

In the first scenario, the code is being processed before the browser has finished parsing the HTML, resulting in the element not being present in the DOM when an attempt is made to reference it. This issue can be resolved by waiting for the document to indicate that it has completed loading.

The second problem arises from immediately calling the birth function followed by the whereIsTheChildren function. As a result, the AJAX request is still pending, meaning the necessary results have not been received. To rectify this, the call to whereIsTheChildren should be placed inside the success callback for the AJAX request.

An example solution has been provided below using plain JavaScript and PHP - simply adjust the PHP file request with your own for CGI.

getKidCount.php

<?php
    echo "3";
?>

index.html

<!doctype html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}

function myAjaxGet(url, successCallback, errorCallback)
{
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function()
    {
        if (this.readyState==4 && this.status==200)
            successCallback(this);
    }
    ajax.onerror = function()
    {
        console.log("AJAX request failed to: " + url);
        errorCallback(this);
    }
    ajax.open("GET", url, true);
    ajax.send();
}

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded(evt)
{
    //birth(3, byId("Marry") );
    myBirth( byId('Marry') );
}

function myBirth(parentElem)
{
    myAjaxGet('getKidCount.php', onAjaxSuccess, onAjaxFail);

    function onAjaxSuccess(ajax)
    {
        var numKids = parseInt(ajax.responseText);
        for (var i=0; i<numKids; i++)
        {
            var div = document.createElement('div');
            div.id = ("child-"+i);
            parentElem.appendChild(div);
        }
        document.getElementById("test-output-1").innerHTML = parentElem.children.length;   // now there are 3 children
        whereIsTheChildren();
    }
    function onAjaxFail(ajax)
    {
        alert("Ajax failed. :(");
    }
}

function whereIsTheChildren()
{
    document.getElementById("test-output-2").innerHTML = byId('Marry').children.length;   // there are 0 children
} 

/*
function birth(xkids, mom)
{
    for( var i = 0; i < xkids; i++ )
    {
        mom.appendChild(document.createElement("div"));
        mom.children[i].setAttribute("id", "child-"+i);
    }
    document.getElementById("test-output-1").innerHTML = mom.children.length;   // now there are 3 children
} 

function birth(mom)
{
    $.ajax(
    {url: "/cgi-bin/count.cgi",   // return 3 for sure
     success: function(xkids)     // xkids is 3
     {
         for( var i = 0; i < xkids; i++ )
         {
             mom.appendChild(document.createElement("div"));
             mom.children[i].setAttribute("id", "child-"+i);
         }

         document.getElementById("test-output-1").innerHTML = mom.children.length;   // now there are 3 children
     }
     document.getElementById("test-output-2").innerHTML = mom.children.length;   // now there are 0 children
} 
*/
</script>
</head>
<body>
    <div id='test-output-1'></div>
    <div id='test-output-2'></div>
    <div id='Marry'></div>
</body>
</html>

Answer №2

Revamped for representation in DOM and console.log output

function giveBirth(childCount, mother) {
  var mom = document.querySelector(mother);
  console.log('Mother: '+mom.id);
  for (var i = 0; i < childCount; i++) {
    mom.appendChild(document.createElement("div"));
    mom.children[i].setAttribute("id", "child-" + i);
    mom.children[i].innerHTML = mom.children[i].id;
  }
  console.log(mom.id+' has '+mom.children.length+' children');
  
  var display = document.createElement("output");
  document.body.appendChild(display);
  display.value = mom.id + ' ' + mom.children.length;
}

giveBirth(3, '#Marry');
giveBirth(5, '#Liz');
giveBirth(2, '#Betty');
div {
  outline: 1px solid black;
  width: 100px;
  height: 30px;
}
output {
  outline: 1px solid red;
  color: red;
  margin: 10px auto;
  padding: 2px;
  float: left;
}
.mom {
  outline: 1px dashed blue;
  width: 100px;
  height: auto;
  padding: 5px;
  display: inline-block;
}
<div id="Marry" class="mom">Marry</div>
<div id="Liz" class="mom">Liz</div>
<div id="Betty" class="mom">Betty</div>

Answer №3

Have you implemented this code within the window.onload event handler? It seems to be functioning correctly, you can check out this code snippet

window.onload=function(){
function createFamily(kids, parent)
{
    for( var i = 0; i < kids; i++ )
    {
        parent.appendChild(document.createElement("div"));
        parent.children[i].setAttribute("id", "child-"+i);
    }

    document.getElementById("test-output-1").innerHTML = parent.children.length;   // now there are 3 children
} 

var parentElement = document.getElementById("Parent"); // currently no child
createFamily(3, parentElement);

function locateChildren()
{
    document.getElementById("test-output-2").innerHTML = parentElement.children.length;   // there are 0 children
} 
locateChildren();
}

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

Implementing Event Handlers for Multiple Textareas Using Jquery on a Webpage

The functionality of my script is exactly how I want it to be, but I am facing an issue when trying to replicate it on a page. The jQuery code manipulates textarea boxes based on button clicks, however, I now need each textarea box to have its own set of b ...

Tips for implementing automatic line wrapping in a PDF document using React-PDF

I am experiencing an issue with a PDF rendering where very long words are not wrapping onto a new line, instead overflowing the container and disappearing off the page. Below is the setup causing this problem. The styles are listed followed by the actual ...

What is the process to include an image file in a JSON object using PhoneGap?

Having trouble saving an image in JSON. Managed to access the mobile camera with the provided code: var pictureSource; // source of the picture var destinationType; // sets the format of returned value // Wait for PhoneGap to connect with the device / ...

What is the proper way to indicate the pointer to the current element within the array?

How can I modify a code that displays a list of posts? import React from "react"; type respX = { "id": any, "userId": any, "title": any, "body": any, } interface PropsI { } interface StateI { data: respX []; } export class Compone ...

Issues with jQuery focus function in Internet Explorer 11

Is there a way to set the focus on an anchor tag using the URL? Anchor Tag: <a id='714895'>&nbsp;</a> URL: jQuery Code: try { if(document.URL.indexOf("?ShowAllComments=True#") >= 0){ var elementClicked = "#" +location.hre ...

What is the best approach to removing a component by utilizing the children prop in React?

I am currently working on a specific scenario: In my project, I have a component called Foo with a property named bar If the bar property is set to true, then I need to display the Bar component that is nested inside the Foo component If the bar prop ...

The mute feature in Discord.js along with setting up a muterole seems to be malfunctioning and encountering errors

Currently, I am working on implementing a mute command feature. The main goal is to have the bot automatically create a role called Muted if it doesn't already exist, and then overwrite the permissions for every channel to prevent users with that role ...

issue with eval() function

I am attempting to convert a JSON string from my .php file using the eval() function, but it is not working. The browser console shows a SyntaxError: expected expression, got '<'... However, when I comment out the line where eval() is used an ...

Using openssl stream with node.js

I am facing an issue with my server running on TLS 1.0. Whenever I run the command below, it keeps giving me an endless stream of data on the terminal: ~$ openssl s_client -connect 'serveraddress':5000 The output is a real-time XML data stream ...

Retrieve the parameter values in PHP that were passed from AngularJS

This is my first time working with PHP and AngularJS. I am trying to pass parameters from AngularJS to a PHP file, where they will be used in an INSERT query. I have set up an XMLHttpRequest to call the PHP file (addsubscriber.php?par1=val1&par2=val2) ...

Retrieve the next 14 days starting from the current date by utilizing Moment.js

Looking to display the next 14 days in a React Native app starting from today's date. For example, if today is Friday the 26th, the list of days should be: 26 - today 27 - Saturday 28 - Sunday 01 - Monday 02 - Tuesday ............ 12 - Friday Is ther ...

Checking data input from an external PHP file and validating dynamically added table row values using Ajax

I'm currently working on a form with dynamic values, such as adding table rows on button click using jQuery. Now, I also want to validate the data before inserting it into my database. To achieve this, I am performing validation with an external PHP ...

The performance of the Ajax Jquery remove function leaves something to be desired

My table has items with a delete button for each row. To achieve this, I created the following Ajax function: $(document).ready(function() { $(".destroy-device").click(function(e) { e.preventDefault(); var id = $(this).attr("data-id"); $.aj ...

Incorporate the title of the article into the URL instead of using the ID

I have a collection of hyperlinks leading to various articles. Here is an example: <a ui-sref="post-view({ id: post._id })">...</a> When clicked, these links generate hrefs like this: href="/blog/546cb8af0c0ec394d7fbfdbf", effectively taking ...

What is the best way to eliminate duplicate values from an Array in ReactJS?

Hi there, I'm new to JavaScript and React. I need some help with a project I found on the React blog. I want to try solving it in my own way. This is the content of todoList.js: const todoList = [ {category: 'Sporting Goods', price: &a ...

Can anyone figure out why this code is not functioning properly? It seems to be targeting the body element and all of

Currently, I am utilizing jqtouch to create a mobile website. In addition to this, I am incorporating a gallery image slider into the website. However, I have encountered an issue where the images do not display when placed between <div id="project_name ...

Guide to making two text boxes with SimpleDialog in jQuery Mobile

I came across the link below, but unfortunately it's not working for me. jQuery Mobile SimpleDialog with two Inputs? Is there anyone who can assist me after reviewing the code snippet provided below? <script type="text/javascript> ...

Refreshing a webpage post initial loading using Next.js

Having trouble with my checkout route ""./checkout"" that displays embedded elements from Xola. The issue arises when using client-side routing as the checkout page requires a manual refresh to load correctly and show the Xola elements on the DOM ...

What is the recommended approach for handling broken pipe errors in Flask when the client disconnects unexpectedly?

During development using Flask, I have set up a view for an AJAX request like so: @application.route('/xyz/<var>/', methods=['GET']) def getAjax(var): ... return render_template(...) In addition, I have enabled threaded= ...

Listen for events in a child process in NodeJS

I am currently utilizing the node child_process API https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options var child = child_process.spawn(cmd, val, options); Within the child process, I make use of the followin ...