简体   繁体   中英

How to select last element in Selenium Webdriver using Javascript?

I create a script to verify that an element is successfully added. The added element always at the end of the page or become last element in different div. I am using selenium webdriver and javascript. Here's HTML code

<div class="row">
<div class="form-group col-sm-2 col-xs-12">
        <label>Entity Name</label>
        <input value="ttax" class="form-control entity-name" disabled="">
</div>
</div>
<div class="row">
<div class="form-group col-sm-2 col-xs-12">
       <label>Entity Name</label>
       <input value="Room" class="form-control entity-name" disabled="">
</div>
</div>

I tried this

let new_entity = await driver.findElement(By.css("div:nth-child(2) > div.form-group.col-sm-2.col-xs-12 > input").last()
let entity_value = await new_entity.getAttribute('value')
expect(entity_value).to.be.eq(entity_name)

But I got error element.last() is not function

Can anyone help me? I can not find references about selenium webdriver in javascript, most of them using java. ss

Here when you want to use the last or first element then we have to get an element array. Instead of findElement, we can use findElements

let new_entity = await driver.findElements(By.css("..")).last();

let entity_value = await new_entity.getAttribute('value'); expect(entity_value).to.be.eq(entity_name);

As the added element always becomes the last element to verify the added element you need to locate the last-child of the parent element which you haven't shown us in the HTML within the question. So to locate the last-child you can use the following based Locator Strategy :

  • Using css :

     let new_entity = await driver.findElement(By.css("immediateParentTag div:last-child > div.form-group.col-sm-2.col-xs-12 > input"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM