0

I was writing some playwright tests and there was situation where I wanted to extract the text from span with text "span-2". See below snippet -

<div data-testid="some-div">
    div-1
    <div>
      div-2
    </div>
    <span>span-1
     <span>span-2</span>
    </span>
</div>

I know there are number of ways to get it and I have found one as well but while I was going through the playwright docs, I found some text based methods that we can call on the locator objects, like

allInnerTexts(), allTextContents(), innerText(), selectText(), textContent()

As of now I am aware of innerText() method and gives the inner text inside the element, like below.

<div data-testid="some-div">
    hello-1
</div>

so await page.getByTestId("some-div").innerText(); will give "hello-1"

What are these other used methods used for? Docs doesn't have much examples. It would be great if I can get some examples around these method and if any one of these methods can be used (directly or indirectly) to solve my problem above?

Thanks in advance!

utkarsh-k
  • 836
  • 8
  • 17

1 Answers1

3
  • allInnerTexts will grab all the elements matching your locator and return an array with their innerText.

  • allTextContents will grab all the elements matching your locator and return an array with their textContent.

  • innerText and textContent will return those values but only for one item. You might want to use first to make sure only one element is matched.

  • selectText is an action. It will select the text of an input.

You can read about the difference between innerText and textContent here.

hardkoded
  • 18,915
  • 3
  • 52
  • 64
  • Just wanted to add - `.inputValue()` is better suited for get values from input boxes? I tried `selectText()` but it didn't work for me for an input box whereas `.inputValue()` method worked just fine. – utkarsh-k Aug 07 '23 at 06:30
  • 1
    @utkarsh-k `selectText` is an action. It will select the text on an input (like right click "Select All" does) – hardkoded Aug 07 '23 at 12:07