Search code examples
javascriptcss-selectorswebdriver-io

Select row-index value by span text


how can I make a selector or an algorithm to return the row-index value with the text of a span?

Html code:

<div class="container">
<div row-index="0">
   <div>
      <div>
         <span>
            <div>
               <span>
               Test1234
               </span>
            </div>
         </span>
      </div>
   </div>
</div>
<div row-index="1">
   <div>
      <div>
         <span>
            <div>
               <span>
               1234test
               </span>
            </div>
         </span>
      </div>
   </div>
</div>
</div>

Expected result: getIndex("1234test"); //will return 1 because row-index='1'

Everything I tried did not help me get to the final solution, will you be able to suggest a solution or give me some advice? I really don't even know where to start


Solution

  • I believe that the easiest way is to use xpath to solve the problem.

    Let's create a function for that:

    async function getRowIndexBy(text) {
      const element = await $(`.//span[normalize-space()='${text}']/ancestor::div[@row-index]`);
    
      return element.getAttribute('row-index');
    }
    

    Usage:

    await getRowIndexBy('1234test'); // will return '1'
    

    This function will find the grandparent element (it's div with row-index attribute in your case) of the element that was found by text (span in your case) and will return the value of the row-index attribute.

    Tested against provided HTML:

    Worked on your HTML