I have the following html:

<div class="dialog-components">
  <h2 class="dialog-title">
    <div class="help-link">
      <a href="http://google.com">Helps</a>
    Expected Result

And I want to getText: "Expected Result". But when I tried to:

String text = driver.findElement(By.cssSelector("div.dialog-components>h2")).getText();

The text is "Helps/nExpectedResult".

How can I get my expected text result?

  • There should be some tag with "Expected result" text , then only it can be get easily. like <p>Expected result</p> Jun 24, 2015 at 10:08
  • @HelpingHands: Yah, I see. But is it possible if we don't have some tags lik e<p> ? Thank you.
    – scorpion
    Jun 24, 2015 at 10:35
  • 1
    You can split on the \n and grab the second line. The real problem here is poor development since they are just putting text willy nilly onto the page.
    – Paul Muir
    Jun 24, 2015 at 11:04
  • @PaulDonny - I agree with your comment. Jun 24, 2015 at 11:06

1 Answer 1


You can get the nodevalue of the element using Javascript


Use executescript to execute JavaScript in the context of the currently selected frame or window

Below is an example in java

Don't forget to add return since you need to return the value to the caller

String expectedresult = (String)((JavascriptExecutor)driver).executeScript("return document.getElementsByClassName('dialog-components')[0].getElementsByTagName('h2')[0].childNodes[2].nodeValue;");

I tested the above code it was working fine

Hope this helps you...Kindly get back if you have any problems

  • @scorpion oh that's gr8....happy to be of help
    – Vicky
    Jun 25, 2015 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.