title: Creating a Selenium getText() method for an element?
body: <p>I am trying to create a Selenium getText() method that gets either the node text OR gets the node+child text of an element.   By default, the Selenium behavior seems to use the Xpath .//string() method of getting text and including the text of immediate children.   I want to take advantage of XPaths power to enable me to get the text in a more targeted way.  My question is: <strong>am I misunderstanding this or is there a better way to accomplish this?</strong></p>
  
  <pre><code>public String getText(By locationOfText, boolean childText)
  {
    By locator = null;
    if ( childText)
    {
      locator = ByChained( locationOfText, By.xpath(".//string()"));
    } else {
      locator = ByChained( locationOfText, By.xpath(".//text()"));
    }
    JavascriptExecutor jse = (JavascriptExecutor)driver;
    String elementText = jse.executeScript("document.evaluate(locator, document.body, null, 
       XPathResult.STRING_TYPE, null);");
  
    return elementText;
  } 
  </code></pre>
  
  <p>Here is an HTML snippet:</p>
  
  <pre><code>&lt;h5 class="class-name clearfix"&gt;Inner Text
     &lt;a class="info-link class-description" href="#"&gt;i&lt;/a&gt;
  &lt;/h5&gt;
  </code></pre>
  
  <p>The problem is that I get the text <strong>Inner Texti</strong> when I use Selenium to do a text call like this:</p>
  
  <pre><code>driver.findElement(".//h5").getText();
  </code></pre>
  
  <p>My expectation was to retrieve the value <strong>Inner Text</strong> .  By creating the method above, I hope to call it like so:</p>
  
  <pre><code>String text = elementHelper.getText(By.xpath(".//h5"),false);
  </code></pre>