find the element in cypress with multiple child elements

Looking for a way to target the first HTML element that contains more than 2 children. Another option is to access the children elements of the first parent element.

<div class="market-template-2-columns">
  <button type="button" class="market-button">
    <span class="button-title">Option1</span>
  </button>
  <button type="button" class="market-button">
    <span class="button-title">Option2</span>
  </button>
</div>
<div class="market-template-2-columns">
  <button type="button" class="market-button">
    <span class="button-title">Option1</span>
  </button>
  <button type="button" class="market-button">
    <span class="button-title">Option2</span>
  </button>
  <button type="button" class="market-button">
    <span class="button-title">Option3</span>
  </button>
  <button type="button" class="market-button">
    <span class="button-title">Option4</span>
  </button>
</div>
<div class="market-template-2-columns">
  <button type="button" class="market-button">
    <span class="button-title">Option1</span>
  </button>
  <button type="button" class="market-button">
    <span class="button-title">Option2</span>
  </button>
  <button type="button" class="market-button">
    <span class="button-title">Option3</span>
  </button>
  <button type="button" class="market-button">
    <span class="button-title">Option4</span>
  </button>
</div>

Answer №1

To select parent elements, you can use the .filter() method

cy.get('.market-template-2-columns')
  .filter((index,element) => element.children.length >= 3)
  .first()    
  .children()

Another option is to use jQuery pseudo-selectors for filtering

cy.get('.market-template-2-columns')
  .filter(':has(button:eq(3))')        
  .first()    
  .children()

Answer №2

To target specific elements in jQuery, the nth-child selector can be quite handy. For example, using nth-child(3) will select elements that are the third child of their parent. To further refine this selection, you can then target the parent element and retrieve the first matching group using eq(0). Once you have the parent element selected, you can then use find to locate and interact with all the buttons within that parent element.

cy.get(".market-template-2-columns .market-button:nth-child(3)").parent(0).eq(0)

// Alternatively, to target the child buttons
cy.get(".market-template-2-columns .market-button:nth-child(3)").parent(0).eq(0).find(".market-button")

// If using tags instead of classes
cy.get("div button:nth-child(3)").parent(0).eq(0).find("button")

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

Issue with Ionic 3 types while using the copyTo function on fileEntry

While working on my Ionic 3 app, I encountered an issue when trying to copy a file to a new directory using the Cordova plugin file. The error message states: Argument of type 'Entry' is not assignable to parameter of type 'DirectoryEntry&a ...

When the down arrow key is pressed, the focus of the radio button is lost

I've been facing a persistent accessibility issue with the main-component in Angular. This component contains four different templates, but depending on the radio button selection, other templates are displayed. The problem arises when these templates ...

Utilizing TypeScript to enhance method proxying

I'm currently in the process of converting my JavaScript project to TypeScript, but I've hit a roadblock with an unresolved TypeScript error (TS2339). Within my code base, I have a class defined like this: export const devtoolsBackgroundScriptCl ...

Configuring the tsconfig outDir will specify where the output files will be stored

What am I missing in the tsconfig settings if I only want to output files in the root directory? If I set it as "rootDir":"src" "outDir":"build", or "rootDir":"src" "outDir":"&q ...

Even after ensuring the proper type checking, I am still receiving the error message "Property 'message' does not exist on type 'object'"

I have the following code snippet: try { // api call } catch (error) { if (typeof error === 'object' && error !== null && 'message' in error) { if (typeof error.message === 'string') { if (error.me ...

Unlocking the union of elements within a diverse array of objects

I have an array of fields that contain various types of input to be displayed on the user interface. const fields = [ { id: 'textInput_1', fieldType: 'text', }, { id: 'selectInput_1', fieldType: 'sel ...

A guide to troubleshooting and resolving the elusive 500 Server Error in Next JS API

Currently, I am in the process of developing a chat bot using the innovative OPEN AI GPT 4 Model within NextJS. However, upon sending a POST request to http://localhost:3001/api/generate, I am faced with a Response displaying a status code of 500 along wit ...

Using ReactJS to pass an arrow function as a prop

Hey, I'm currently facing an issue where I need help creating a React component that can accept the following custom transformation: <CustomComponent transform={e=> {...e, text = e.text.toUpperCase()}}> </CustomComponent> I would real ...

Anticipate the middleware function to either invoke the next function or return a HTTP 400 status code

I am eager to delve into unit testing and am looking to test my Node API. I am utilizing Express with Typescript and Jest for testing. Prior to invoking the controller middleware, I apply the route input validation middleware to verify the validity of the ...

Angular 7 compile error NG8002: Unable to bind object as it is not recognized as a valid property

Currently working on an Angular 7/8 test App. Encountering a compile error Can't bind 'discounter' since it isn't a known property of 'paDiscountEditor' The HTML where the error is occurring is simple... Below are all the nec ...

How to fix the "Module parse failed" issue when importing MP3 files in NextJS 14 TypeScript?

Starting a new NextJS project, I used the command npx create-next-app@latest. Within this project, I created a simple TSX component that takes an imported MP3 file as a prop. 'use client'; import Image from "next/image"; import audioI ...

Why don't my absolute paths work on nested folders in React and Typescript?

Struggling to configure absolute paths in my React project, encountering challenges with nested folders and the use of @ prefix. Here's what I have set up in my tsconfig.json: { "compilerOptions":{ "baseUrl":"src", ...

How can we limit the CSS properties that can be used in an interpolated manner by defining a restricted TS type for CSS props based on emotions?

When dealing with emotions, how can we specify a restricted TS type for the css prop to only allow certain css properties to be interpolated? For instance, consider the following scenario: // This is considered valid css = {{ color: 'white', ...

Utilize the UserService in NestJs to enhance security within the RolesGuard functionality

In my application, I have a module called UserModule that exports the UserService. Here is an example of how it is done: @Module({ imports: [ MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]), MongooseModule.forFeature([{ name: ...

Typescript's confidential variables

Currently, I am delving into the world of Angular2 and familiarizing myself with working with classes in javascript for the first time. I'm curious about the significance of using the private parameter in the constructor, as opposed to simply writing ...

Retrieving the returned value from an Observable of any type in Angular Typescript (Firebase)

I am working on retrieving data from my Firebase User List using the following code: currentUserRef: AngularFireList<any> currentUser: Observable<any>; var user = firebase.auth().currentUser; this.currentUserRef = this.af.list('usuarios ...

"Transferring a C# dictionary into a TypeScript Map: A step-by-step

What is the correct way to pass a C# dictionary into a TypeScript Map? [HttpGet("reportsUsage")] public IActionResult GetReportsUsage() { //var reportsUsage = _statService.GetReportsUsage(); IDictionary<int, int> te ...

Extending the type of parameters in TypeScript

I am trying to call a function from my UI library with a parameter type that extends the original (Suggestion) type by adding more properties. I found a resource that suggests it is possible here: https://github.com/Microsoft/TypeScript/issues/2225 (in the ...

The 'resp' parameter is assumed to have an unspecified type, shown as 'any'. This is an error in Angular

} ErrorHandler(response){ console.debug(response.json()); } DataHandler(response){ this.ClientModels = response.json(); } I have developed two functions to handle error and success responses, but an error message is showing up saying "para ...

Exploring the capabilities of Vue combined with Typescript and Audio Worklets

I've encountered a challenge with configuring Vue to compile audio worklets. Specifically, I am facing a similar issue to this problem that has already been resolved, but using Typescript instead of JavaScript. My approach was to include the ts-loader ...