简体   繁体   中英

How to get only text from element - Protractor Javascript

I am trying to get raw text only from a html element. For example:

<h1>This is a <br> Test</h1>

I want to be able to get the text inside <h1> minus the <br> ....

this is a Test

I have tried:

browser.driver.findElement(By.tagName('h1')).getAttribute('textContent');

browser.driver.findElement(By.tagName('h1')).getAttribute('innerHTML');

browser.executeScript("return arguments[0].innerHTML;", element(locator));

I don't see any reason why getAttribute('textContent') isn't working, I think that would be the easiest way to get the raw text.

I know there have been some breaking changes with protractor for angular over the last few releases, that led me to use browser.executeScript .

Update

Please only post a solution if you have directly used it with protractor.

This should work.

element(by.css('h1')).getText().then((value: string) => {
    const val: string = value.replace(/[\n\r]/g, '');
});

A handy cheatsheet for protractor .

And will highlight what Andrew Lohr posted. Always check the docs :)

The answer's so far have not addressed getting just the text without <br> .

Yong's response was what led me down the path to find the solution.

For those interested. The most simple way is to get the text and use replace to switch the <br> with a space instead.

    element(by.(xxx)).getText().then(function(text) { 
      text = text.replace(replace(/(\r\n|\n|\r)/gm," "); 
      console.log(text);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM