Search code examples
xpathplaywright

Find element where sibling child has text


I have such a div:

<div class="mat-form-field-infix ng-tns-c66-377">
   <mat-select _ngcontent-dgg-c495="" role="combobox" aria-autocomplete="none" aria-haspopup="true" class="mat-select ng-tns-c69-378 ng-tns-c66-377 ng-star-inserted" aria-labelledby="mat-form-field-label-339 mat-select-value-217" id="mat-select-216" tabindex="0" aria-expanded="false" aria-required="false" aria-disabled="false" aria-invalid="false">
      <div cdk-overlay-origin="" class="mat-select-trigger ng-tns-c69-378">
         <div class="mat-select-value ng-tns-c69-378" id="mat-select-value-217">
            <!---->
            <span class="mat-select-value-text ng-tns-c69-378 ng-star-inserted" style="">
               <span class="mat-select-min-line ng-tns-c69-378 ng-star-inserted">Delivery Correction</span><!----><!---->
            </span>
            <!---->
         </div>
         <div class="mat-select-arrow-wrapper ng-tns-c69-378">
            <div class="mat-select-arrow ng-tns-c69-378"></div>
         </div>
      </div>
      <!---->
   </mat-select>
   <span class="mat-form-field-label-wrapper ng-tns-c66-377">
      <label class="mat-form-field-label ng-tns-c66-377 ng-star-inserted" id="mat-form-field-label-339" for="mat-select-216" aria-owns="mat-select-216" style="">
         <!---->
         <mat-label _ngcontent-dgg-c495="" class="ng-tns-c66-377 ng-star-inserted">Adjustment Reason</mat-label>
         <!----><!---->
      </label>
      <!---->
   </span>
</div>

I need to get a mat-select by looking at mat-label text(). Tried playing with following, following-sibling, descendant but without any success. Working solution for me is: //mat-label[text()='Adjustment Reason']/ancestor::node()[3]/mat-select, but I don't like using ancestors or parents, as it's not a robust solution.

How can I improve this path?

P.S. Replaced image with a snippet.


Solution

  • I'd do something like this:

    //*[.//mat-label='Adjustment Reason']/mat-select
    

    Essentially I'm selecting the div (or other parent element of mat-select) based on there being a descendant mat-label with a value of Adjustment Reason.

    It might be a little more performant if we first check to see if the element has a child mat-select:

    //*[mat-select][.//mat-label='Adjustment Reason']/mat-select