The final child element is null when using lastElementChild

For my current Javascript project, I am tackling the task of dividing the page into two separate div elements. The left div is populated with randomly positioned images, and then I utilized the .cloneNode() method to duplicate this on the right side, excluding the last image element.

Up to that point, everything was functioning correctly. However, I encountered an issue when trying to attach an event handler to the final element in the left div. Despite the presence of child nodes within the div as expected, the lastElementChild() method returned null. I have included the code snippet below along with a comment pointing out the problematic section. Any assistance would be greatly appreciated!

<!DOCTYPE html>
<html>
<head>
<style>
    img {position: absolute}
    div {position: absolute; height: 500px; width: 500px}
    #right {border-left: solid black; left: 500px}
</style>

<script>

<!-- All previous sections are working flawlessly -->

    function generateFaces(){

        var theLeftSide = document.getElementById("left");

        var numberFaces = 5;

        for (i = 0; i < numberFaces; i++){
            var random_x = Math.random()*400;
            var random_y = Math.random()*400;
            var image = document.createElement("img")
            image.src = "smile.png";
            image.setAttribute("style","top: " + random_y + "px;" + "left: " + random_x + "px;");
            theLeftSide.appendChild(image);
        }

        var theRightSide = document.getElementById("right");

        leftSideImages = theLeftSide.cloneNode(true);
        theRightSide.appendChild(leftSideImages);
        theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);
    }


</script>

</head>
<body onload = "generateFaces()">
    <h1> Game </h1>
    <p> Instructions </p>

    <div id = "right"></div>

    <div id = "left"> </div>

    <script>

    <!-- Issue arises in this portion of the script -->

    var temp = document.getElementById("left");
    console.log(temp); // displays <div> with its children <img>

    var temp2 = temp.lastElementChild;
    console.log(temp2); // returns null

    </script>

</body>

</html>

Answer №1

The onload event of the body will only trigger after the execution of the JavaScript in your 'problem script'.

The sequence of events is as follows:

  • The elements h1, p, #left, and #right are added to the DOM

  • Script #1 executes, logging the empty #left div and the lastElementChild as null.

  • The body's onload event triggers, and script #2 runs (the generateFaces() function), inserting the <img> tags into the DOM.

To resolve this issue, ensure that script #1 runs after script #2:

<body onload="handleLoad()">

and here is the corresponding JS code:

function handleLoad() {
    generateFaces()
    logStuff()
}

function logStuff() {
    var temp = document.getElementById("left");
    console.log(temp); // displays <div> with its children <img>

    var temp2 = temp.lastElementChild;
    console.log(temp2); // logs <img>
}

It might seem like the #left already has images when script #1 runs due to the asynchronous nature of the console log. Consequently, the value logged may be different than the actual content at the time of calling console.log().

You can observe this behavior by adjusting the setTimeout duration for the generateFaces() function call.

Additionally, note that the generateFaces() function creates multiple elements with the same id in the DOM, which should be rectified.

Answer №2

Your generateFaces() function is triggered when the body finishes loading. However, your second script will only run once the window has completely loaded.

This means that when the second script executes, there is no temp.lastElementChild available, resulting in a null value.

You can resolve this issue by following this code snippet:

<!DOCTYPE html>
<html> 
<head>
<style>
img {position: absolute, height: 30px; width: 30px;}
div {position: absolute; height: 500px; width: 500px}
#right {border-left: solid black; left: 500px}
</style>
</head>
<body onload="generateFaces()">
<h1> Game </h1>
<p> Instructions </p>

<div id="right"></div>

<div id="left"> </div>
<script>


function generateFaces()
{
    console.log('y');
    var theLeftSide = document.getElementById("left");

    var numberFaces = 5;

    for (i = 0; i < numberFaces; i++){
        var random_x = Math.random()*400;
        var random_y = Math.random()*400;
        var image = document.createElement("img")
        image.src = "smile.png";
        image.setAttribute("style","top: " + random_y + "px;" + "left: " + random_x + "px;");
        theLeftSide.appendChild(image);
    }

    var theRightSide = document.getElementById("right");

    leftSideImages = theLeftSide.cloneNode(true);
    theRightSide.appendChild(leftSideImages);

    theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);

    loaded();

}

<script>

function loaded() {

var temp = document.getElementById("left");
console.log(temp); 

var temp2 = temp.lastElementChild;
console.log(temp2); 

}

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

What is the best way to assign the "active" class to a navigation list item using JavaScript within Bootstrap 4?

Update: just to clarify, I'm working on activating the navbar button based on the current page. I have a navigation bar set up and I am trying to dynamically add an "active" class to the li element when you are on that specific page. However, for som ...

Difficulty in altering the background of an input box

I am attempting to design a textbox that changes its background color to green when the correct answer is submitted, and to red for an incorrect answer. Unfortunately, nothing is happening for either option. document.querySelector('form').addE ...

What are the implications of using eval() to interpret function parameters?

I've recently utilized Hopscotch to create a interactive tour on my Website. To implement this, you need to create a JavaScript object as a parameter to trigger the startTour() function which will kick off the tour. For instance, in this case, the tou ...

Creating a state in React may lead to an endless loop

Currently, I am working on retrieving data from a Firebase real-time database and storing it in an array named 'users'. The goal is to use this array to set the "post" state. However, there seems to be an issue with the line "setPost(users);" as ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...

Showing button based on a particular value

I am trying to dynamically display a button based on the value of the sendSMS property for the logged-in user. I have added this property in the viewer model, which is connected to the user's base model. However, I am encountering difficulties with us ...

There are two different ways to set a hyperlink in HTML. One method is by using the href attribute, where you provide the URL inside the quotation marks. The other

While browsing, I stumbled upon this interesting piece of JavaScript code: onClick="self.location.href='http://stackoverflow.com/'" I incorporated this code into my website, and it seems to have the same effect as using the href attribute. Sin ...

Unable to obtain return value in AngularJS controller or view

I have been working on a geolocation and reverse geocoding application. I have a function that is triggered by a button click to call a function in my controller which then calls my service. While the service is able to retrieve values, I am unable to get ...

Decoding user input parameters within a vue module

It seems like I am hitting a wall when it comes to finding solutions for this particular issue. Currently, I have a component that is supposed to retrieve data from a file and display it. My intention is to only pass the filename to the component so that ...

What is the best way to adjust the screen to display the toggle element when it is opened?

Here is the code I'm currently using to create a toggle button that shows or hides extra content when clicked: $(".toggle .button").click(function() { $(this).next().slideToggle('fast'); }); The issue I am encountering is that if t ...

Tips for updating checkbox values in the database to 1 when selected and 0 when deselected

Managing Database Information <?php if(isset($_POST["insert"])) { $conn = mysqli_connect("localhost", "root", "", "databaseappfeature"); if(isset($_POST["insert"]) == "1"){ $query = "UPDATE appfeature SET feature_switch = ('".$_POST["ins ...

SWR Worldwide Settings

I am trying to configure a global SWRConfig in my Next.js application. In my _app.js file, I have the following setup: import '@/styles/bootstrap.min.css'; import "@/styles/globals.css"; import Layout from "@/components/Layout"; import { SWRConfi ...

Discover the secrets to replicating the mesmerizing horizontal scrolling menu akin to the

What is the most effective way to create a horizontal menu similar to the innovative Google picture menu? Could someone kindly share their knowledge and provide the code for achieving the same outcome? ...

Update the promise status to reflect any changes

While attempting to modify the button text based on the promise status, I created a custom directive for this purpose. Below is the code snippet for my custom directive: .directive('myDir',function(){ return { scope: { ...

What is the best way to include a class with Knockout JS?

After going through the basic Knockout tutorial and examining various examples, I decided to try it out myself on jsFiddle. However, I encountered some issues as my attempts did not quite work. The goal is simple - I just want to add the class open to a d ...

Ways to showcase a variable's value in conjunction with text using .html() method

Hello, I need assistance with printing a value in a popup window. Below is the code I am using: "code" $('#warning').html('<p style="font-size: 12px;padding-top: 13px;">The updated list value is <p>' + var11); https://i.s ...

Tips for transferring information obtained from an API to my custom HTML page

As a novice in web development, I recently created a simple weather report website using the OpenWeather API. While I successfully fetched data from the API, I encountered an issue trying to display this data on my HTML page. Despite utilizing DOM manipu ...

Combine the click event and onkeydown event within a single function

I have a function that sends a message when the Enter key is pressed. However, I also created a button to send a message, but when I call this function, the message doesn't send, even though I added a click event. function inputKeyDown(event, input ...

What could be causing the submenus in my intricate menu component to lose focus when input is entered?

I'm currently working on developing a menu using the MUI Menu component. The goal is to have a popup input control (such as Autocomplete, TextField, Select, or a custom form) appear when a menu item is clicked, based on the choice made from the menu. ...

Guide on how to perform a POST request within a service worker?

I am faced with the challenge of sending a POST request to the back-end every time a client clicks on a Push notification from the front-end, in order to confirm that the client has received the notification. Here is the system I currently have in place f ...