Selenium Last Element

Profile picture for user arilio666

Demo Website:  http://www.automationpractice.com

We will click on the T-Shirts tab using last child.

selenium last child

    CSS Selector Last Child Selenium

    Step 1: Select Parent

    ul.menu-content 

    Now here above selector covers the entire body of the three tabs under which they are present. So in this case it is the parent.

    Step 2: Select all child

    Under this ul tag, there are 3 li tags which are the respective tags of Women, Dresses, and T-shirts.


    selenium find last child element

    ul.menu-content>li 

    Above selector will return all 3 elements.

    Step 3: Select last child

    Now use :last-child to select the last child

    ul.menu-content>li:last-child

    Selenium XPath Last Child

    Step 1: Select Parent

    //ul[contains(@class,'menu-content')]

    Step 2: Select all Child

    //ul[contains(@class,'menu-content')]/li

    Step 3: Select Last Child using last() method

    (//ul[contains(@class,'menu-content')]/li)[last()]

    Example

    public class AppTest 
    {
        WebDriver driver;
    	
        @BeforeClass
        public void befClass()
        {
            System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir") + "//drivers//chromedriver");
            driver = new ChromeDriver();
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
            driver.get("http://www.automationpractice.com");
        }
    	
        @Test
        public void LoginTest()
        {
            WebElement lastChildCSS = driver.findElement(By.cssSelector("ul.menu-content>li:last-child"));
            WebElement lastChildXPath = driver.findElement(By.cssSelector("(//ul[contains(@class,'menu-content')]/li)[last()]"));
            
            lastChildCSS.click();
            lastChildXPath.click();
        }
    }