Deleting and inserting an element in the Document Object Model

I am currently working on developing a framework and need to create a directive called cp-if. Unlike the existing cp-show directive, where I can simply change the visibility of an element to 'none' and then make it visible again, with the cp-if directive I need to dynamically create and delete DOM objects.

import {MapDom} from '../map-dom';
import {Common} from '../../common';

export class CPIf {

 private element: any;
 private map: MapDom;
 private attribute;
 private initialDisplay;

 constructor(_element: HTMLElement, _map: MapDom) {
     this.element = _element;
     this.map = _map;
     this.attribute = Common.getAttributeCpIf(this.element);

     Common.getScope(this.element).$on('$onInit', () => this.init());
 }

 init() {
     try {
         Common.evalInContext(this.attribute, Common.getScope(this.element).scope) ? this.show() : this.hide();
     } catch (ex) {
         this.hide();
     }
 }

 hide() {
     this.element.remove()
 }

 show() {
     console.log(this.element);
 }

}

While I can remove the object from the DOM, I struggle to recover it when the action goes to the show() function. I apologize if my explanation is not very clear.

Answer №1

To resolve this issue, you can use the createComment() method as shown below:

import {MapDom} from '../map-dom';
import {Common} from '../../common';

export class CPIf {

 private element: any;
 private map: MapDom;
 private attribute;
 private initialDisplay;
 private elementComment;

 constructor(_element: HTMLElement, _map: MapDom) {
     this.element = _element;
     this.initialDisplay = this.element.style.display || 'block';
     this.map = _map;
     this.attribute = Common.getAttributeCpIf(this.element);
     this.elementComment = document.createComment('cpIf ' + this.attribute);
     Common.getScope(this.element).$on('$onInit', () => this.init());
 }

 init() {
     try {
         Common.evalInContext(this.attribute, Common.getScope(this.element).scope) ? this.show() : this.hide();
     } catch (ex) {
         this.hide();
     }
 }

 hide() {
     this.element.replaceWith(this.elementComment);
 }

 show() {
     this.elementComment.replaceWith(this.element);
 }

}

Answer №2

While I can't confirm the effectiveness of your proposed solution, I encountered a similar issue not long ago and opted for a different approach.

In my case, the linter was unable to identify the .remove() method in relation to the HTMLElement type. However, it did acknowledge the presence of .removeChild(). Consequently, I devised a workaround by creating a chain of parent elements leading up to the grandparent element, which ultimately executed removeChild on its immediate child element. Here's an example snippet:

(An 'if' statement was utilized to appease the linter and forestall any concerns related to potential null objects)

if (listItemElement && listItemElement.parentNode && listItemElement.parentNode.parentNode) {
  listItemElement.parentNode.parentNode.removeChild(listItemElement.parentNode);
}

Although not the most elegant fix, this method effectively resolved the issue. It is plausible that in the future, the linter may come to recognize the simpler .remove() method, thereby streamlining the process.

Answer №3

If you need to remove a DOM element from its parent node, try using the removeChild() method. In case you are working with Internet Explorer browser, remember that remove() may not be supported, so stick to removeChild() for compatibility across all browsers. parentNode.removeChild(element);

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

The error message "Property is not found on type 'Object'" suggests that the property being accessed does not

I wrote a function called getAll getAll<T>() { return this.http.get(`${environment.apiUrl}/products`); } Here is how I am invoking it: this.productService.getAll() .pipe(first()) .subscribe(products => { debugger let s ...

Instead of leaving an Enum value as undefined, using a NONE value provides a more explicit

I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below. enum DoSomething { VALUE1, VALUE2, VALUE3, } f ...

Include a new module in the declarations NgModule utilizing ts-morph

Currently, I am utilizing the ts-morph library and my objective is to add a new component to the declarations: This is my initial setup: @NgModule({ declarations: [], imports: [], providers: [], }) Here is what I am aiming for: @NgModule({ declarations: [ ...

TypeScript(error:2532): object may be undefined despite null or undefined check

Currently, I am developing a Discord-bot using TypeScript which includes a command to retrieve information from an airport. To do this, users only need to provide the 4-character ICAO code that identifies the specific airport. However, due to potential use ...

In Typescript, ambient warnings require all keys in a type union to be included when defining method parameter types

Check out this StackBlitz Example Issue: How can I have Foo without Bar, or both, but still give an error for anything else? The TypeScript warning is causing confusion... https://i.stack.imgur.com/klMdW.png index.ts https://i.stack.imgur.com/VqpHU.p ...

Utilizing sourcemaps in ionic for seamless linking

I've encountered an issue with source maps or a similar feature. After inserting console.log(...) in my code, the message appears in the console but links to the compiled JavaScript file instead of the original TypeScript file. Have I overlooked som ...

Determining block time based on block number within Polygon Mumbai Testnet

Is there a dependable method to identify the production time of a specific block in Polygon Mumbai Testnet using only its block number? I am unable to utilize an Api for this purpose and am seeking a more user-friendly computational solution. Any suggest ...

Integrating HTTP JSON responses into HTML using Ionic 2, Angular 2, TypeScript, and PHP: A comprehensive guide

Currently in the midst of developing my first Ionic 2 app, however, my understanding of typescript is still limited.. I aim to execute the authenticate() method within my constructor and then to: Retrieve the entire JSON response into the textarea and/o ...

How should one begin a new NativeScript-Vue project while implementing Typescript support in the most effective manner?

Is it possible to incorporate Typescript into Vue instance methods? I found guidance on the blog page of nativescript-vue.org. Whenever I initiate a new nativescript-vue project using vue init nativescript-vue/vue-cli-template <project-name>, some w ...

What is the best way to simulate a function within an object using Jest and Typescript?

I am currently working on a function that calls the url module. index.svelte import {url} from '@roxi/routify'; someFunction(() => { let x = $url('/books') // this line needs to be mocked console.log('x: ' + x); }); ...

Can the variable name within a function be retrieved?

How can I retrieve the variable name (user_name1 or user_name2) from a sample function (GetUserName()) within itself? This variable name is required to create an object with the same name on the server side for data synchronization purposes. function GetU ...

Leverage TypeScript generics to link props with state in a React class-based component

Can the state type be determined based on the prop type that is passed in? type BarProps = { availableOptions: any[] } type BarState = { selectedOption: any } export default class Bar extends React.Component<BarProps, BarState> { ...

The 'formGroup' property cannot be bound as it is not recognized as a valid property of 'form' in Angular 7

I tried implementing a login feature using web API with Angular 7, but encountered an error when using <form [formGroup]="loginForm" (submit)="loginFormSubmit()">. What could be causing this issue? login.component.html <form [formGroup]="loginFo ...

Unable to load the node modules

In my development journey, I created an ASP.NET MVC project using Angular 2 in Visual Studio 2017 and set up node for package management. Here is a snippet from the package.json file: { "version": "1.0.0", "name": "asp.net", "private": true, ... ...

When switching tabs, Ion-select should not reload the selected name

Whenever I switch tabs and then return to the previous tab in Ionic, the select field that was previously set becomes null, even though the page is still loading and the variable is populated. <ion-header color="primary"> <ion-navbar> &l ...

Using React with Typescript and ie18next to fetch translations from an external API

In the past, I have experience working with i18next to load translations from static json files. However, for my current project, I need to load all translations from an API. How can I achieve this? Additionally, how can I implement changing the translat ...

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

The term "primordials is not defined" is a common error

Whenever I attempt to run Gulp using the task runner, I am encountering this error message. I suspect it may be due to updating my npm project, but I'm unsure about how to resolve it. Should I try installing a different version of npm? >Failed to r ...

How can I pass DOCUMENT in Angular?

In my directive, I use dependency injection to access the DOCUMENT and set up an event listener: constructor(@Inject(DOCUMENT) private document: Document) {} ngOnInit() { this.document.addEventListener('click', this.clicked, true); } @Bound ...

delayed updating of property not visible in angular 10 immediately

I needed to hide a div based on a condition, so I decided to use the hidden property like below: <div [hidden]="isControlDisplayed()?false:true"> The isControlDisplayed() method determines whether to show or hide the div based on the value ...