Xpath: Find an element whose descendant has got a certain attribute value

StackOverflow https://stackoverflow.com/questions/23564482

  •  18-07-2023
  •  | 
  •  

سؤال

I have the following elements in a web page. I would like to fetch the element with id "pmt-id-234" which has got a descendant with classname as type2.

<div id="cards">
    <div id="pmt-id-123" class="payments">
        <div>
            <div class="type1">Text1</div>
        <div>
    </div>

    <div id="pmt-id-234" class="payments">
        <div>
            <div class="type2">Text1</div>
        <div>
    </div>
</div>   

Notes:

  1. I don't know the highlighted part in "pmt-id-123", hence direct query with ID is not possible.
  2. The div with class="typeX" can be nested multiple levels down.

What is tried? The below gives me two div elements.

'//*[@id="cards"]//*[starts-with(@id,"pmt-id-")]'

Now, how to fetch the div which has a descendant div with class="type2"

The following din't yield any results.

'//*[@id="cards"]//*[starts-with(@id,"pmt-id-")//*[contains(@class, "type2")]]'
'//*[@id="cards"]//*[starts-with(@id,"pmt-id-")][contains(@class, "type2")]'

Please let me know how to do this?

هل كانت مفيدة؟

المحلول

I'd test against div rather than * if there are only divs there.

This XPath will select the div under one with an id of cards that has an id that starts with pmt-id- and also has a descendant div of class type2:

'//div[@id="cards"]//div[starts-with(@id,"pmt-id-") and .//div[contains(@class, "type2"]]'

Note that you may have to take extra care with the matching against the @class to avoid matching type22 or abctype2 if such types are possible.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top