selenium get li element based on index position and click the checkbox

learner :

I have this HTML now using Selenium I ant to toggle the li element with given index position say 1, where it indicates I want to click the toggle checkbox for spring.

<ul id="todo-list" data-woven="abc">
<li class="active" data-index="0">
    <div class="view">
        <input class="toggle" type="checkbox">
        <label>Java</label>
        <button class="destroy"></button>
    </div>
    <input class="edit">
</li>
<li class="active" data-index="1">
    <div class="view">
        <input class="toggle" type="checkbox">
        <label>Spring</label>
        <button class="destroy"></button>
    </div>
    <input class="edit">
</li></ul>

I am completely new to selenium so not able to understand how can we achieve this.

I know to get the UL elements using the code:

driver.findElement(By.id("todo-list"));

Now how can get the li element based on its index and click the corresponding checkbox.

DebanjanB :

To click on the checkbox element with respect to the ancestor <li> nodes index attribute you can use either of the following Locator Strategies:

  • cssSelector:

    driver.findElement(By.cssSelector("ul#todo-list li.active[data-index='1'] input")).click();
    
  • xpath:

    driver.findElement(By.xpath("//ul[@id='todo-list']//li[@class='active' and @data-index='1']//input")).click();
    

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=416318&siteId=1