Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation.

import { Draggable, DragTarget } from '../Models/eventlisteners';
import { HeroValues } from '../Models/responseModels';
import { Util } from './Util';

export class Heroes implements Draggable, DragTarget {
  static instance: Heroes;
  hostElement: HTMLDivElement = document.getElementById(
    'app'
  )! as HTMLDivElement;
  templateElement: HTMLTemplateElement = document.getElementById(
    'tmpl-hero-overview'
  ) as HTMLTemplateElement;
  element: HTMLCollection;

  heroes!: HeroValues;
  imagesLoaded: number = 0;

  constructor() {
    const importedNode = document.importNode(
      this.templateElement.content,
      true
    );
    this.element = importedNode.children as HTMLCollection;
  }

  async retrieveHeroes() {
    // The code to retrieve and process hero data...
  }

  render() {
    // Code for rendering heroes...
  }

  dragStartHandler(event: DragEvent) {
    // Handler for drag start event...
  }

  // Other event handler methods...

  configure() {
    // Configuring the event listeners...
  }

  private updateDOM() {
    // Updating the DOM after loading images...
  }

  static getInstance() {
    // Singleton pattern implementation...
  }
}

I've isolated the issue to this particular section of code. When I access this.element, which is an HTMLCollection needed for later use, it behaves unexpectedly. Initially, in the first two console.logs, it displays the expected properties that were defined in the constructor. However, after the second forEach-loop, it loses all its properties and has a length of 0.

I attempted creating a copy of this.element before the forEach loop by using a variable with Array.from(this.element).slice(), but it did not resolve the problem.

I then considered if Array.from() inadvertently transforms this.element, but according to the documentation, it creates a copy rather than altering the original.

Could anyone provide assistance with this issue?

Edit: I opted not to include my entire code as the problem appears to be pinpointed. However, I can share more if necessary.

Answer №1

Here's a better solution:

Assign this.element as Array.from(importedNode.children)

This way, this.element creates a snapshot of importedNode.children, ensuring that any movement of child nodes won't impact it.

The issue arises when you use:

Array.from(this.element).forEach....

In this case, this.element still references importedNode.children, meaning any changes will affect both variables, leading to inconsistencies if elements are moved.

Remember, element.children is dynamic; additions or removals reflect instantly - a useful feature.

Note that setting this.element=importedNode.children doesn't make a copy but acts as a reference to the same object.

Finally, consider this:

this.hostElement.insertAdjacentElement('beforeend', el);

This action removes el from its original position (importedNode.children) and relocates it within this.hostElement.children. Consequently, the element gets removed from importedNode.children and thus affects this.element as well.

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

Tips for creating a customized dropdown menu that opens upwards without relying on Bootstrap

Looking for some assistance with creating an animated dropdown menu that slides upwards. Any help is appreciated! $('.need-help').click(function() { $('.need_help_dropdown').slideToggle(); }); .need-help { background:url(../im ...

Using Typescript: Compiling specific files within a directory

According to the documentation for typescript, we have the option in tsconfig.json to manage input files using either the files property where all files are listed, or with the exclude property. I have organized all my source files within a directory named ...

What is the size limit for JSON requests in Node.js?

I am seeking information about the req object in nodeJS. Let's say I have a code that sends data in JSON format to my server using an AJAX POST method. Now, imagine a scenario where a user manipulates my client code to send an excessively large JSON f ...

Tips on transforming a JSON array object into a JSON array

**Background:** I have been utilizing lodash to eliminate the empty key from my JSON data. However, upon removal of the keys, it transforms my array into an object. For instance: { "projection": "Miller", "series": [ { "mapPolygons": { ...

Prevent the mouseup event in jQuery when the mouse has previously been moved

I have a div with a row of span buttons displayed horizontally. Since there are too many buttons to fit on the screen, I want to enable the user to click and drag the entire row of buttons. However, my challenge is to ensure that the button's mouseup ...

guiding user immediately to blog post upon successful login

I recently created a blog with a customized URL like instead of the traditional . Now, my dilemma is that I want to share this URL and have it redirect users to the login page if they are not logged in. Once they log in, I would like them to be redirect ...

Having trouble getting the toggleClass function to work properly?

I'm facing an issue with some straightforward code that I've written. $(function() { $("#tren").click(function() { $("#trens").toggleClass("show"); }); }); .show { color: "red"; } <ul> <li id="tren">Some text</li> < ...

Is it possible for lodash's omit function to return a specific type instead of just a partial type?

Within the following code snippet: import omit from "lodash/fp/omit"; type EnhancerProps = { serializedSvg: string; svgSourceId: string; containerId: string; }; const rest = omit(["serializedSvg", "containerId"])(props); The variable 'rest&a ...

The ngOnInit function is not triggered upon instantiation of an Injectable class

What could be causing the ngOnInit() method not to be called upon resolution of an Injectable class? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable ...

Encountering an error message stating "Unable to read property 'map' of undefined while attempting to create drag and drop cards

I have incorporated the library available at: https://github.com/clauderic/react-sortable-hoc The desired effect that I am aiming for can be seen in this example: https://i.stack.imgur.com/WGQfT.jpg You can view a demo of my implementation here: https:// ...

Modifying an @Input element within a component does not result in any changes being reflected in the parent component

Here is the scenario with my component: @Component({ selector: 'child' }) export class ChildComponent { @Input() childObject: ChildObject; changeObject(newObject: ChildObject){ childObject = newObject; } } After calling ...

I am struggling to make the map method display the specific components I need

Attempting to create a scalable Custom Form using an array of objects and a custom Input field in a React-Typescript project import React, { ChangeEvent } from "react" import { InputField } from "./InputField" interface FormItem { ...

Extracting the value of an HTML element from a string variable in AngularJS

I am facing an issue with my application where the content of an HTML element is received as a template from the server. I am attempting to assign this template, which is essentially a string, and have the variables within the template linked to the contro ...

Issues encountered while establishing a connection to an API in React Native

When attempting to log in a user by connecting to my API, I encountered some issues. It seems that every time my laptop has a different IP address, I need to make changes in the file where the fetch or XMLHttpRequest is located in order for the login proce ...

Guide to using method pointers in PHP

Is there a way to use method pointers in PHP? I've encountered the following error: Fatal error: Call to undefined function create_jpeg() in /Users/sky/Documents/images.php on line 175 This is at line 175: if ($this->ImageType_f[$pImageType]( ...

What is the reason behind JavaScript's restriction on using double comparison operators?

What is the reason behind javaScript not supporting double comparison? For example, in 64 < str.charCodeAt(i) && str.charCodeAt(i)<=77, why is it not possible to simplify it to 64 < str.charCodeAt(i)<=77? ...

Adding a clickable button to execute code within a LeafletJS marker!

I'm currently experimenting with adding a button inside a pointer that will log a message to the console. This is simply a test to see if I can execute a method on the marker, but so far I haven't been able to display any text. const marker = L.m ...

Updating user data when logged in on multiple browsers can be tricky. Here's how to make sure that

I am currently using the express-session middleware to store user sessions in a Mongo collection. What is the most effective way to update all user sessions when changes are made from one session? For instance, if a user updates their email in session A, ...

Ways to eliminate a specific array from another array using JavaScript

0: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_amount: 9500, toppings: 500, …} 1: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_amount: 9500, toppings: 500, …} 2: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_am ...

After the page is reloaded, apply a class to the divs by selecting them based on the "data" attribute

I have a set of four cards labeled "card", each representing different body parts: eyes, torso, arms, and legs. <div class="card" data-lesson="eyes">eyes</div> <div class="card" data-lesson="torso">torso</div> <div class="card" ...