I am trying to get the text of an element using Selenium getText() method and using innerText property of an element and compare the output.

HTML code:

    <h1>  DEF <p>  Demo   Shot   <span>   Taken   by   me    </span></p>   </h1>

Selenium code:

    Demo Shot Taken by me
    Demo Shot Taken by me

As per the Selenium doc:

getText() method gets the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.

So, I expect both the outputs should be same. But in this case, the output of getText() and getAttribute("innerText") is completely different. Any reason ?

  • 3
    I believe the definition of getText() that you provide is taken from javascript selenium bindings. Not from Java. Java api does not mention innerText in that method description. It just states that the text is provided "as rendered" selenium.dev/selenium/docs/api/java/org/openqa/selenium/…
    – Alexey R.
    Sep 25, 2020 at 20:17
  • @AlexeyR. I read it here that the getText method gets the innerText of this element... Sep 26, 2020 at 14:37
  • It's obviously not a documentation
    – Alexey R.
    Sep 26, 2020 at 16:55

1 Answer 1


It does something different. Java implementation shows:

public String getAttribute(String name) {
  return stringValueOf(
    execute(DriverCommand.GET_ELEMENT_ATTRIBUTE(id, name))


public String getText() {
  Response response = execute(DriverCommand.GET_ELEMENT_TEXT(id));
  return (String) response.getValue();

Going further, they are calling different W3C API, the first one calls: Get Element Attribute and the second one calls: Get Element Text.

I guess (not 100% sure) one level deeper they are calling different things in DOM. One calls .textContent while other calls .innerText.

Now it might be the same or not - depending on the browser type, selenium version and so on... ;)

  • Thanks for the answer. I tested the getAttribute("innerText"), getAttribute("textContent") and getText() method on the element having simple text <span>Mumbai</span> and observed that all of them return the same output Mumbai. You are correct, the behaviour is not consistent, it depends on the descendant text nodes of the element and its formatting(i.e. space, tabs, new line etc..). Sep 26, 2020 at 15:57
  • 1
    I have found, just testing with some vanilla JavaScript, that innerText seems to return a trimmed result, while textContent returned raw content.
    – corsiKa
    Sep 26, 2020 at 22:24

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.