简体   繁体   中英

how to get count of child elements using selenium web-driver for nodejs

I have searched at numerous places but I am not getting an answer

here is my html :

    <form id="search_form_homepage" >
    ...
<div class="search__autocomplete" style="display: block;">
    <div class="acp-wrap js-acp-wrap">
        <div class="acp" data-index="0"><span class="t-normal">elephant</span>cheap auto</div>
        <div class="acp" data-index="1"><span class="t-normal">elephant</span>asia</div>        
        ...
        ...
        <div class="acp" data-index="2"><span class="t-normal">elephant</span>africa</div>
    </div>
    ...
</div>
</form>

I simply need to get the count of the <div> present within the div with class acp-wrap js-acp-wrap

I can reach this point but am stuck beyond :

let xyz = driver.findElements(By.className(".acp-wrap js-acp-wrap>div"));

You would need to use By.css to get element by this: .acp-wrap js-acp-wrap > div . Also, your selector is not correct. When you select an element by class, you need to put a period before the class name: .acp-wrap.js-acp-wrap > div (remove the space between acp-wrap and js-acp-wrap , too).

Here is how you can get that element now:

let xyz = driver.findElements(By.css(".acp-wrap.js-acp-wrap > div"));

Now to get the count, you can get the length property of xyz . But since driver.findElement returns a promise, you need to use async-await. You can create a function:

async function getCount() {
  let xyz = await driver.findElements(By.css(".acp-wrap.js-acp-wrap > div"));
  const count = xyz.length;
  return count;
}

EDIT

When you call the function:

getCount().then(function(count) {
  // your stuff there
});

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