How do I extract visible text of a div that changes dynamically?

Here we look at extracting text of a div whose visible text changes completely.

For example, let us say there is a div that identifies the total number of items added to a shopping cart. Here, the total represents the complete text and can change dynamically depending on how many items were added.

If you need to extract partial text that changes dynamically, refer to the FAQ on extracting partial text.

This requirement can be solved as follows.
  1. We need to identify the div first, to retrieve its text.

    Sahi identifies a div through the visible text, by default. But since this keeps changing dynamically, it cannot be used to identify the element.

    So we need to use one of the following methods to get a unique identifier.
    • Use one of the Alternatives from the Alternatives: dropdown in the Controller Record tab, which does not change when the visible text changes.
    • Or identify the element in relation to some other anchor element using a Relation API such that the identifier remains unique.
  2. Once we have the unique element identifier, use _getText() to get the visible text of the element.

    var $text = _getText(_div("/someclass/"));
    // Here the div is identified by a regular expression matching the class name.
    //The class name uniquely identifies the element here.