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!
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.