Getting the count of child elements who match a certain text using protractor
-
21-12-2019 - |
Question
I have a parent <div>
in a non Angular page. Inside that parent <div>
there are many child <div>
s. In those child <div>
s I have many tags with data. The structure of the HTML is as follow:
<div class="row clearfix">
<div class="col206">
<p class="name">User16</p>
<p class="project-name">Manager</p>
<p class="telefone"></p>
</div>
<div class="col206">
<p class="name">User16</p>
<p class="project-name">Manager</p>
<p class="telefone"></p>
</div>
<div class="col206">
<p class="name">User15</p>
<p class="project-name">Developer</p>
<p class="telefone"></p>
</div>
<div class="col206">
<p class="name">User14</p>
<p class="project-name">Developer</p>
<p class="telefone"></p>
</div>
<div class="col206">
<p class="name">User13</p>
<p class="project-name">Tester</p>
<p class="telefone"></p>
</div>
<div class="col206">
<p class="name">User12</p>
<p class="project-name">Terster</p>
<p class="telefone"></p>
</div>
<div class="col206">
<p class="name">User11</p>
<p class="project-name">Developer</p>
<p class="telefone"></p>
</div>
<div class="col206">
<p class="name">User10</p>
<p class="project-name">Support</p>
<p class="telefone"></p>
</div>
</div>
I want to test the project using Protractor and get the count of those elements whose project name is tester. How to do that?
Solution
For now there is no built-in locator to perform easily what you want to do. There is one locator that allow us to search by text but it is only for button element.
I proposed a pull request to be able to search elements with css selector and text but it is not accepted yet.
Meanwhile, you can build your own specific locator:
by.addLocator('projectName', function() {
var projectSelector = '.row div'; // probably need some refinement
var projectName = arguments[0];
var using = arguments[1] || document;
var elements = using.querySelectorAll(projectSelector);
var matches = [];
for (var i = 0; i < elements.length; ++i) {
var element = elements[i];
var elementText = element.innerText || element.textContent;
if (elementText === projectName) {
matches.push(element);
}
}
return matches;
});
And then you can count like this:
element.all(by.projectName("Tester")).count()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow