Reputation: 1
I am using Protractor to test my web application. I try to count the number of child elements inside a parent div element, such like:
<div id="abc">
<div class="a">..</div>
<div class="b">..</div>
<button>..</button>
</div>
The result should be 3, but I have no idea how to count the number with both div and button. Thank you!
Upvotes: 0
Views: 667
Reputation: 15499
I cannot speak to a protractor solution - but this is easy with straight javascript - and since you have tagged javascript- i thought I would share.
By using querySelectorAll and referencing the parent element and then using the direct descendant / child selector ">
" with the wildcard selector "*
" - you can find alll elements that are the direct children of the parent div, then use .length
to find the number of items.
const elements = document.querySelectorAll('#abc > *');
const elementsLength = elements.length;
console.log(elementsLength); // gives 3
<div id="abc">
<div class="a">..</div>
<div class="b">..</div>
<button ="a">..</button>
</div>
EDIT - with a couple of minutes of Google searching - I found a protractor site that gave info on querying the DOm and returning a protractor test - note that I do not know Protractor at all so am using this as a suggestion for the dom query -
cite - inspred by - http://www.webdriverjs.com/find-elements-using-javascript-protractor/
describe('Locating element numbers using JS', function () {
it('Identify number of children elements', function () {
browser.get("http://angularjs.org");
element.all(by.js(function () {
const elements = document.querySelectorAll('#abc > *');
return elements;
})).then(function (webElements) {
const elementsLength = webElements.length;
expect(elementsLength).not.toBe(0);
});
});
});
Upvotes: 1
Reputation: 13712
You can use *
in css selector to get all child of any tag:
const child_amount = await element(by.css('div#abc > *')).count()
Upvotes: 0