Having difficulty locating the index of the column labeled `Clients` within a table; the result being -1

Having some trouble locating the index of the column name Customers within a table using jQuery/javascript. No matter what I try, it always returns -1

let tableDatacy = "Results_Table";
let columnName = "Customer";
let tableHeaders = [];
tableHeaders = Cypress.$(`[data-cy=${tableDatacy}] > thead:nth-child(0) > tr:contains(${columnName})`);
let columnPosition = tableHeaders.toString().indexOf(columnName);

<table data-cy="Results_Table">
   <thead class="HeaderOriginal">
    <tr class="tablesorter-headerRow">
    <th class="hideExport hidePrint tablesorter-header" data-column="0" tabindex="0" unselectable="on" style="user-select: none;"><div class="tablesorter-header-inner">&nbsp;</div></th>
  <th class="ajaxOrder tablesorter-header" order="customer" data-column="3" tabindex="0" unselectable="on" style="user-select: none;">
       <div class="tablesorter-header-inner">
       <a href="javascript: void(0);" class="desc">Customers</a>
       </div>
   </th>
   <th class="hideExport" data-column="0" tabindex="0" unselectable="on" style="user-select: none;"><div class="tablesorter-header-inner">&nbsp;</div></th>
  <th class="ajaxOrder tablesorter-header" order="customer" data-column="3" tabindex="0" unselectable="on" style="user-select: none;">
       <div class="tablesorter-header-inner">
       <a href="javascript: void(0);" class="desc">Machine</a>
       </div>
   </th>
   </tr>
   </thead>
 </table>

Answer №1

If you prefer using only jQuery, the corresponding code snippet would look like this:

const tableIndex = Cypress.$(`[data-cy="Results_Table"]`)
  .find(`th:has(a:contains("Customers"))`)
  .index()

Please Note: Ensure that the page is fully loaded before executing any jQuery operations, for example:

beforeEach(() => {
  cy.visit(...)
})

it('...', () => {

  const tableIndex = Cypress.$(`[data-cy="Results_Table"]`)
    .find(`th:has(a:contains("Customers"))`)
    .index()
  ...
})

Answer №2

To access the index value of your columns, you can utilize the invoke('index') method. For more information, refer to the Jquery Docs.

cy.get('[data-cy="Results_Table"]')
    .find(`th:contains('Customers')`)
    .invoke('index')
    .then((index) => {
        cy.log(index); // This will output 1
    });

If you need to use the index value later in the same test, you can assign it using .as()

cy.get('[data-cy="Results_Table"]')
    .find(`th:contains('Customers')`)
    .invoke('index')
    .as('indexValue')

cy.get('@indexValue').then((indexValue) => {
    expect(indexValue).to.eq(1)
    // You can now use the index value as needed
})

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

"Failure in bundling with NodeJS using nexe and fusebox

I am attempting to convert a nodejs application into an .exe file. I initially tried using pkg, but encountered errors with half of the node-modules. Now, I am experimenting with a different method. However, when I run the following command: nexe index.js ...

Utilizing ng-model with invisible input field

UPDATED: Experimenting with a new approach: <input class="form-check-input deflog-check" type="checkbox" ngTrueValue = "1" ngFalseValue = "0" ng-value="chk_mail"> Now trying to retrieve the value in AngularJS like so: object2Edit.notification = N ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

Looking for assistance with overriding kendo UI validation requirements

I'm looking to customize the date validation in my code to validate the date as DD/MM/YYYY. Here's my current code snippet and I'm getting an error message that says: Unable to get property 'methods' of undefined or null referen ...

Moving the legend around in vue-chartJS

As someone just starting out with Vue-ChartJs, I've become quite intrigued by this: https://i.sstatic.net/j1S0z.png I'm wondering how to move the legend to the bottom of the graph. Can anyone help me with that? ...

experimenting with a TypeScript annotation

I have created a simple decorator that can trigger either stopPropagation() or preventDefault() based on certain conditions. I have thoroughly tested this decorator in my application and am confident that it works correctly. However, I encountered an issue ...

JavaScript: Specialized gravity diagram

To better understand the issue I am experiencing, please take a look at the image linked below: The concept and problem I am facing is related to creating a weight chart similar to the one shown in the picture or on this site , here is the description of ...

What is causing my Fabric.js canvas to malfunction?

Here is the link to my JSFiddle project: http://jsfiddle.net/UTf87/ I am facing an issue where the rectangle I intended to display on my canvas is not showing up. Can anyone help me figure out why? HTML: <div id="CanvasContainer"> <canvas id ...

The regular expression pattern ((xn--)?[a-z0-9]+(-[a-z0-9]+)*.)+[a-z]{2,} is functional when used on regexpal.com, however, it does not yield the

Within the code snippet below, the regular expression in the "pattern" variable is specifically designed to only match the criteria mentioned in the comment (which requires a minimum of 1 letter followed by a dot, and then two letters). var link = "Help" ...

Does a DOM API exist specifically for querying comment nodes within the document?

My document contains a debugging comment that appears as follows: <!--SERVER_TRACE {...}--> Is there a method to search the DOM and access this specific node? I would prefer a vanilla JavaScript solution, without relying on any external libraries. ...

When utilizing exit-hook with process.on('SIGTERM'), child_process spawn requires two control-c commands to exit properly

I have the following program running: const { spawn } = require("child_process"); const exitHook = require("exit-hook"); exitHook(() => { console.log("Leaving"); }); spawn("my-program", ["my-args"], { stdio: "inherit" }); // Long running server ...

Exploring the filter method in arrays to selectively print specific values of an object

const array = [ { value: "Value one", label: "Value at one" }, { value: "Value 2", label: "Value at 2" }, { value: "" , label: "Value at 3" } ...

Trigger the callback function once the datatables DOM element has finished loading entirely

Hello there! I have a question regarding datatables. Is there any callback function available that is triggered after the datatables DOM element has finished loading? I am aware of the callbacks fnInitComplete, but they do not serve my purpose. Specificall ...

How can you use HTML, CSS, and JavaScript to group objects with one color and then change the color of one specific object?

I have a set of 6 labels that act as buttons. When one is clicked, it changes from white to blue. If another label is clicked, the previously blue label turns white and the newly clicked one turns blue. Currently, the code below sets all labels to white b ...

Error with Cross-Origin Resource Sharing (CORS) upon inserting a parameter within an Express application

I'm completely stumped as to why this isn't functioning properly. My express app is deployed on Heroku and here's the code: var urlMetadata = require('url-metadata') var express = require('express') var cors = require( ...

Obtaining a worldwide JavaScript variable through AJAX JSON query

Hello, I have encountered an issue while using this code for my AJAX JSON request. When attempting to make jsonObj a global variable and then console.log() it, the debugger console shows that it is always coming up as undefined. To explain my question fur ...

Utilize Javascript to extract information from an array of XML objects

I have an XML object that I need to parse in order to extract startdate and end date data. My goal is to compare and group appointments with the same date together, but I don't have much experience manipulating XML - I'm more comfortable with JSO ...

Having trouble parsing FormData in the django backend

Greetings everyone! I hope you are all doing well. I've been working on a custom form that needs to be sent to the Django backend using an AJAX request. The challenge I'm facing is that when I wrap the form into FormData, it works fine on the fro ...

Show component depending on the lifecycle of another component

I recently encountered a problem with one of my custom components. I developed a "Chargement" Component (Loading in French) for a project I am currently working on. The component is a basic circular spinner with a dark background that indicates to the use ...

employing the d3.queue method to defer execution until receiving the AJAX response

Seeking examples of integrating AJAX, d3, and PHP to extract data from a database and create graphs. Any guidance would be appreciated. I am currently using d3 to generate a force chart based on database information retrieved through AJAX and PHP. I have ...