The process of removing and appending a child element using WebDriverIO

I am trying to use browser.execute in WebDriverIO to remove a child element from a parent element and then append it back later. However, I keep receiving the error message "stale element reference: stale element not found". It is puzzling because keeping a reference to the removed child should not be causing this issue.

const selector = '#unique-id';
let childElement = await browser.execute(selector => document.querySelector(selector).parentElement.parentElement, selector);
const parentElement = await browser.execute(c => c.parentElement, childElement);
childElement = await browser.execute((p,c) => p.removeChild(c), parentElement, childElement);
await browser.execute((p,c)=>p.appendChild(c), parentElement, childElement);

Answer №1

This method successfully worked for me when testing on a sample website. Feel free to adjust and customize it to fit your specific needs.

  it('stack', async () => {
    await browser.url('https://www.saucedemo.com/');
    const parent = await $('.login_credentials_wrap-inner');
    const child = await $('.login_password');
    await child.waitForEnabled(5000);
    console.log(`Child Text: ${await child.getText()}`);
    const childSrc = await child.getHTML();
    console.log(`Child HTML: ${childSrc}`);
    console.log(`Step 0: ${await parent.getHTML()}`);
    await browser.execute((p) => {
      let chi = p.lastElementChild; // Refer to notes below
      return chi.remove();
    }, parent);
    console.log(`Step 1: ${await parent.getHTML()}`);
    await browser.execute((c, k) => c.insertAdjacentHTML('beforeend', k), parent, childSrc); // Refer to notes below
    console.log(`Step 2: ${await parent.getHTML()}`);
    expect(await $('.login_password').getText()).toContain('Password for all users:');
  });

Console Output:

[0-0] Child Text: Password for all users:
[0-0] secret_sauce
[0-0] Child HTML: <div class="login_password"><h4>Password for all users:</h4>secret_sauce</div>
[0-0] Step 0: <div class="login_credentials_wrap-inner"><div id="login_credentials" class="login_credentials"><h4>Accepted usernames are:</h4>standard_user<br>locked_out_user<br>problem_user<br>performance_glitch_user<br></div><div class="login_password"><h4>Password for all users:</h4>secret_sauce</div></div>
[0-0] Step 1: <div class="login_credentials_wrap-inner"><div id="login_credentials" class="login_credentials"><h4>Accepted usernames are:</h4>standard_user<br>locked_out_user<br>problem_user<br>performance_glitch_user<br></div></div>
[0-0] Step 2: <div class="login_credentials_wrap-inner"><div id="login_credentials" class="login_credentials"><h4>Accepted usernames are:</h4>standard_user<br>locked_out_user<br>problem_user<br>performance_glitch_user<br></div><div class="login_password"><h4>Password for all users:</h4>secret_sauce</div></div>

Note: Modify the code based on the element order. Refer to documentation for insertAdjacentHTML here and lastElementChild here.

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

Exploring i18nNext integration with antd table in React

Presently, this is the UI https://i.stack.imgur.com/CMvle.png App.tsx import "./styles.css"; import MyTable from "./MyTable"; export default function App() { const data = [ { key: "1", date: "2022-01- ...

What are the best scenarios for implementing abstraction in Angular?

Throughout my experience, I have encountered Java EE, .Net, and various other enterprise application architectures. In each case, there was always an abstract upper class - like AbstractService for generalizing the service layer. However, in Angular, I ha ...

There was an error during compilation: Module not detected - Unable to locate './xxxx'

Looking for help with importing a file from another folder into my Next.js project. I need assistance with the correct syntax and paths as I am encountering an error. Here is a link to the screenshot of the error: Below are the two files: //src/component ...

Enhance Graphql Queries with TypeOrm using Dynamic Filters

I am currently working on building a graphQL query system using Apollo, typescript, and TypeOrm. At the moment, I only have one table called users in my database. I am creating a getUsers GraphQL query which retrieves all users from the table. With the hel ...

The condition will be false if a number is present, even if it is zero

I am facing an issue with a class containing an optional field called startDateHour: export class Test { startDateHour?: number; // more fields, constructor etc. } I need to perform an action only if the startDateHour exists: if (test.startDateHour ...

How to start Angular2 prototype with an object literal

export abstract class GridColumn { public field?: string; public sortField?: string; public header?: string; public footer?: string; public sortable?: any = true; public editable?: boolean = false; public filter?: boolean = true ...

JSX conditionally rendering with an inline question: <option disabled value="">Select an option</option>

Yes, I can confirm that the inline is functioning properly because in the Convert HK to Passive Segment paragraph at the top I am seeing the expected output. What I am aiming for is to display a "Choose a hotel" message when there are multiple hotels in th ...

Unable to locate module: Issue: Unable to locate '@angular/cdk/tree' or '@angular/material/tree'

Currently utilizing Angular 5 and attempting to create a tree view that resembles a table layout. https://stackblitz.com/edit/angular-hhkrr1?file=main.ts Encountering errors while trying to import: import {NestedTreeControl} from '@angular/cdk/tree ...

Getting a "function is not defined" error in Angular 6 while using it within a nested function

I'm facing an issue related to typescript, where the following code is causing trouble: private loadTeams = function(){ let token = sessionStorage.getItem('token'); if(token !== undefined && token !== null && token ...

Generating a new object from a TypeScript class using JavaScript

Currently, I am facing an issue while attempting to call a JavaScript class from TypeScript as the compiler (VS) seems to be having some trouble. The particular class in question is InfoBox, but unfortunately, I have not been able to locate a TypeScript d ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...

Best practice for importing pipeable RxJs operators in Angular CLI/WebPack rollup

In the earlier versions of Angular CLI, specifically those before 1.5.0, it was common practice to import all RxJs operators and statics into a single file for easy usage throughout the application. For example: rxjs-operators.ts // Statics import &apos ...

Encountering an error when attempting to add the 'shelljs' module to an Angular 2 TypeScript project

I am facing an issue with including the shelljs library in my Angular 2 TypeScript project. I have already added the shelljs.d.ts file to the node_modules/shelljs directory. Below is my package.json configuration: "name": "myproj1", "description": "myp ...

typescript library experiencing issues with invalid regex flags in javascript nodes

I am facing an issue while attempting to import a plain JavaScript module into a Node application written in TypeScript. The error below is being thrown by one of the codes in the JavaScript module. b = s.matchAll(/<FILE_INCLUDE [^>]+>/gid); Synta ...

Issue: Unable to locate a matching object '[object Object]' of type 'object'. NgFor can solely bind to data structures like Arrays and Iterables

I am facing an error that says "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." I am trying to create a Notification list but I can't figure out w ...

Ngrx effects are not compatible with earlier versions of TypeScript, causing issues with functionality

Seeking assistance with my Ionic 3 App utilizing ngrx/store and ngrx/effects. However, upon attempting to run the app, I consistently encounter the following error: TypeScript Error A computed property name in a type literal must directly refer to a bui ...

Bespoke Socket.io NodeJS chamber

I am currently developing an application involving sockets where the requirement is to broadcast information only to individuals within a specific room. Below is a snippet of the code from my server.ts file: // Dependencies import express from 'expre ...

The custom validation feature in Angular 4 is failing to function as expected

Currently, my focus is on Angular 4 where I have developed a custom validator for checking CGPA values (to ensure it is between 2.0 and 4.0). Although the predefined `Validators.required` works fine, my custom validator seems to be not triggering as expect ...

Unable to delete event listeners from the browser's Document Object Model

Issue at hand involves two methods; one for initializing event listeners and the other for deleting them. Upon deletion, successful messages in the console confirm removal from the component's listener array. However, post-deletion, interactions with ...

Transform a string into a boolean value for a checkbox

When using v-model to show checked or unchecked checkboxes, the following code is being utilized: <template v-for="(item, index) in myFields"> <v-checkbox v-model="myArray[item.code]" :label="item.name" ...