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

Tips for waiting for an Http response in TypeScript with Angular 5

Is it possible to create a function that can retrieve a token from a server, considering that the http.post() method generates a response after the function has already returned the token? How can I ensure that my function waits for the http.post() call t ...

Tips on revealing TypeScript modules in a NodeJS environment

Currently, I am working on developing a TypeScript library. My goal is to make this library compatible with both TypeScript and JavaScript Node projects. What would be the most effective approach for achieving this? Should I create two separate versions ...

Using Typescript types or a linter can help avoid mistakenly rendering the raw function in JSX instead of its executed return value

Seeking a resolution to prevent the recurring mistake I often make, as shown below: export function scratch_1 (props: scratch_1Props): ReactElement | null { function renderA (): string { return "A"; } function renderB (): string { ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

I am unable to employ filtering in TypeScript

Hey there, I'm trying to filter some JSON data randomly by using this function, but I keep running into an error with my variable called filteredArray. The error message says "Property 'filter' does not exist on type 'Dispatch<SetSta ...

Tips on modifying the selected type key name through Pick?

I currently have this structure: type Product = { name: string } and I am looking to extract the name property and use it in a different type declaration like so: type NewProduct = Pick<Product, 'name'> Now, I want to rename name as new ...

When typing declarations are used, they clarify whether the entity being referenced is an Object or

I am currently working on aligning the Dockerode run typings to match the actual implementation. The issue arises when I invoke run as TypeScript consistently identifies the return value as a Promise. It seems that TypeScript is having trouble distinguish ...

Definition for intersecting types

I am trying to define a function that can take two objects of different types but with the same keys: function myFunc(left, right, keys) { // simplified: for (const key of keys) { console.log(key, left[key] === right[key]) } return { left, rig ...

"Displaying the Material Input TextBox in a striking red color when an error occurs during

After referring to the links provided below, I successfully changed the color of a textbox to a darkish grey. Link 1 Link 2 ::ng-deep .mat-form-field-appearance-outline .mat-form-field-outline { color: #757575!important; } Although this solved the ...

Get every possible combination of a specified length without any repeated elements

Here is the input I am working with: interface Option{ name:string travelMode:string } const options:Option[] = [ { name:"john", travelMode:"bus" }, { name:"john", travelMode:"car" }, { name:"kevin", travelMode:"bus" ...

Using Typescript and React to render `<span>Text</span>` will only display the text content and not the actual HTML element

My function is a simple one that splits a string and places it inside a styled span in the middle. Here's how it works: splitAndApplyStyledContent(content: string, textType: string, separator: string) { const splittedContent = content.split(separat ...

Create an object that may have any number of keys, but must have at least one key defined

Is there a way to accomplish this task? type Plant = "rose" | 'tulip' | 'daisy' type PlantCollection = { [p in Plant]?: number } const validPlantCollection: PlantCollection = { rose: 1, daisy: 2 } const emptyCollectionShouldBeRejec ...

Changing the function to operate asynchronously

How can I convert the following code into an asynchronous function? It is currently returning referralUrl as undefined: controller async createReferralUrls() { this.referralUrl = await this.referralService.generateReferralUrl(this.userData.referral ...

Webpack 4 combines the power of Vue with the versatility of Typescript classes and JavaScript code simultaneously

Currently, I am in the process of migrating JS files to Typescript with the objective of being able to utilize both JS and Typescript classes within Vue. While I understand that I can convert Vue scripts into Typescript, I prefer not to do so at this momen ...

Is it possible to write TypeScript and execute it directly with Node?

I am attempting to write some basic typescripts but I am encountering an issue with the setup below: node src/getExchangeAndTickerList.ts import * as mkdirp from 'mkdirp'; ^^^^^^ SyntaxError: Cannot use import statement outside a module ...

The issue arises when TypeScript declarations contain conflicting variables across multiple dependencies

My current project uses .NET Core and ReactJS. Recently, I updated some packages to incorporate a new component in a .tsx file. Specifically, the version of @material-ui/core was updated from "@material-ui/core": "^3.0.3" to "@material-ui/core": "^4.1.3" i ...

The module `perf_hooks` could not be resolved

Trying to integrate perf_hooks library from the nodeJS Performance API into my React Native project has been quite a challenge. Here's the snippet of code I've been working with: import {performance} from 'perf_hooks'; export const mea ...

Utilizing D3 to fetch geographic data in the form of a TopoJSON file for U.S. counties

After retrieving a set of coordinates, the goal is to use D3 to find the corresponding county from a U.S. TopoJSON file. Here is an example code snippet: navigator.geolocation.getCurrentPosition(function(position) { let coordinates: [number, number] = [p ...

Activate the function only once the display has finished rendering all items from ng-repeat, not just when ng-repeat reaches its last index

Currently, I am generating a list using ng-repeat and each iteration is rendering a component tag with a unique id based on the $index value. The implementation looks like this: <div ng-if="$ctrl.myArr.length > 0" ng-repeat="obj in $ctrl.myArr"> ...

Avoid triggering onClick events on all rows when clicking, aim for only one row to be affected per click

I have a unique situation where I have a table containing rows with a button in each row. When this button is clicked, it triggers an onClick event that adds two additional buttons below the clicked button. The Issue: When I click on a button, the onClick ...