Search code examples
c#seleniumselenium-webdriverxpathfindelement

Selenium C#: How to identify element without particular child element


I have following elements on the page:

<span class="card-body">
    <span>No tickets</span>
    <h5 class="card-title">..</h5>
    <p class="card-text card-text-top">..</p>
    <p class="card-text">..</p>
</span>

There are several the same card-body elements in the DOM, however, I would like to identify the first one that does not contain <span>No tickets</span> child element.

What is the most correct locator which I should use, while working with selenium and C#?


Solution

  • To identify the first element that does not have a decendent <span>No tickets</span> element you can use the following xpath based locator strategy:

    //span[@class='card-body'][not(.//span[text()='No tickets'])]
    

    Your effective line of code will be:

    driver.FindElement(By.XPath("//span[@class='card-body'][not(.//span[text()='No tickets'])]"))
    

    Snapshot of the example:

    ticket