A0__oN
A0__oN

Reputation: 9100

Getting the text from the Element -- exclude the text of inner element

I've a HTML as Below

<div class="someClass">
     LNAME, FNAME MNAME
    <a class="button" onclick="#">This is Button</a>
</div>

I want to get the text inside the div.someClass i.e LNAME, FNAME MNAME.

But I'm getting following

LNAME, FNAME MNAME 
This is Button

I'm using driver.findElement(By.cssSelector("div.someClass")).getText();

I'm aware that above code is giving me the text of div.someClass element as a whole.

How can I extract the value of just div.someClass but not inner element. For example I've given, I want output as

LNAME, FNAME MNAME

Upvotes: 0

Views: 332

Answers (2)

parishodak
parishodak

Reputation: 4666

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

For removing text from sub-elements you have to handle it yourself, like explained below:

public String getTopElementText(By by)
{
   WebElement topElement = driver.findElement(by);
   String originalText = topElement.getText();

   // get all child elements who has innerText and stringlength is greater than 0
   List<WebElement> children = topElement.findElements(By.xpath("*[string-length(text()) > 0]"))

   for(WebElement element :  children)
      orginalText = originalText.replace(element.getText(), "");

  return originalText;
}

Upvotes: 1

Paras
Paras

Reputation: 3235

//a[@class='button']/preceding-sibling::text()

Upvotes: 1

Related Questions