Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting text from a node

I have a piece of HTML like this:

<a href="/something">
     Title
    <span>Author</span>
</a>

I got a WebElement that matches this HTML. How can I extract only "Title" from it? Method .getText() returns "Title\nAuthor"...

like image 795
zorglub76 Avatar asked Dec 14 '11 13:12

zorglub76


People also ask

What is a text node?

A text node encapsulates XML character content. A text node can have zero or one parent. The content of a text node can be empty. However, unless the parent of a text node is empty, the content of the text node cannot be an empty string.

How do I get Div text?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.

How do I get text in JavaScript?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants.


1 Answers

You can't do this in the WebDriver API, you have to do it in your code. For example:

var textOfA = theAElement.getText();
var textOfSpan = theSpanElement.getText();
var text = textOfA.substr(0, textOfA.length - textOfSpan.length).trim('\n');

Note that the trailing newline is actually part of the text of the <a> element, so if you don't want it, you need to strip it.

like image 139
Ross Patterson Avatar answered Nov 15 '22 10:11

Ross Patterson