Rishi Sharma
Rishi Sharma

Reputation: 115

How to get the text of all elements in protractor

I want to fetch all the li texts of suggestions after entering in the google search bar "Webdriver". I have wrote some code like this:

 this.getElements = function(){
  element.all(by.css('ul.sbsb_b')).then(function(text){
      for(var i=0; i < text.length;i++)
      {
          console.log(text[i].getText());
      }
  });
};

On execution I m getting something like:

{ ptor_: 
  { controlFlow: [Function],
     schedule: [Function],
     getSession: [Function],
     getCapabilities: [Function],
     quit: [Function],

instead of text values of Suggestions.

Upvotes: 6

Views: 38620

Answers (6)

Segg3r
Segg3r

Reputation: 466

There is a set of javascript array-like functions in Protractor that allows you to filter() or map() result of async promise. For example if original element.all(by.css('something')) would return list of ElementFinders, map() allows to transform it into array of getText()s, which in resolved state is just an array of strings. You can then use it however you want.

element.all(by.css('something')).map(function(elm) {
  return elm.getText();   
}).then(function(texts) {
  texts.forEach(...);
});

Upvotes: 19

Vijay Bhaskar
Vijay Bhaskar

Reputation: 1

Its an old question but still when i did someElementSelector.getText(); i got a string instead of array, so i split the string based on '\n'

example

someElementSelector.getText().then(function(text){
  var arrayA = text.split("\n");
// this gives me ['one','two','three'] 
})

This gives us the array of text from an element which has multiple texts.

Upvotes: 0

Surendra Jnawali
Surendra Jnawali

Reputation: 3240

We need to specify getText() to get list of text in element.all

<ul class="menu">
   <li>Home</li>
   <li> About Us</li>  
</ul> 

element.all(by.css('.menu li')).getText().then(function(menus) {
    expect(menus.length).toBe(2); //true
    console.log(menus);
});

log output

['Home','About Us']

Need more helper function

Upvotes: 7

LjekiDex
LjekiDex

Reputation: 21

You should do next

this.getElements = function(){
  element.all(by.css('ul.sbsb_b')).getText().then(function(text){
      console.log(text);
  });
};

Upvotes: 0

user3450620
user3450620

Reputation: 61

For looping through every element, you can also do something like:

element.all(by.css('ul.sbsb_b')).each(function(element, index) {
    element.getText().then(function(text) {
        console.log(text);
    });
});

http://angular.github.io/protractor/#/api?view=ElementArrayFinder.prototype.each

Upvotes: 4

Sakshi Singla
Sakshi Singla

Reputation: 2502

To print the value from getText(), you need to resolve the promise using .then()

Something like this:

text[i].getText().then(function(textValue)
{
    console.log(textValue);
});

Regards,
Sakshi

Upvotes: 2

Related Questions