GettingStarted With123
GettingStarted With123

Reputation: 427

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"));

Upvotes: 1

Views: 796

Answers (1)

User456
User456

Reputation: 1301

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
});

Upvotes: 1

Related Questions