2

I need to get the text from an html element which is hidden with css. I know that per the specs innerText will abide the css rules. But the alternative of using textContent ignores line break and tabs which I need to keep in the string.

Is there any way around this?

For simplicity please see the following example:

const inntxt = document.querySelector('.expandable').innerText
console.log(inntxt) // Here we don't get the hidden div's text.

const txtct = document.querySelector('.expandable').textContent

console.log(txtct) // Here the result removes the line break.
.hidden{
  display: none;
}
<div class='expandable'>
  <span class='visib'>
    Red balloon
  </span>
  <br>
  <span class='hidden'>
    Yellow badge<br>Green ribbon
  </span>
</div>

I guess one way around it would be to replace the <br> with my own char like # by appending it instead of the <br>, but there must be a better way no?

UPDATE

To be more clear the end result should be:

For example if you would console.log() the string in node, then the string from our innerText or textContent should be: 'Red balloon\nYellow Badge\nGreen ribbon'

S. Schenk
  • 1,960
  • 4
  • 25
  • 46

3 Answers3

1

It is very unintuitive that textContent doesn't retrieve <br> new lines.

I suggest using a dummy element in Javascript using innerHTML and replacing all <br> with \n<br>.

Take a look at this code, I think it solves your issue:

const expandable = document.querySelector('.expandable')
const auxEl = document.createElement('div')
auxEl.innerHTML = expandable.innerHTML.replace(/(\<br\>)/, '\n$1')
const textContent = auxEl.textContent

console.log({ textContent })

/* Yields
{
  "textContent": "\n  \n    Red balloon\n  \n  \n    Yellow badge\nGreen ribbon\n  \n"
}
*/
.hidden {
  display: none;
}
<div class='expandable'>
  <div class='visib'>
    Red balloon
  </div>
  <div class='hidden'>
    Yellow badge<br>Green ribbon
  </div>
</div>
GMaiolo
  • 4,207
  • 1
  • 21
  • 37
-1

Kindly use the following script to get innerText

const inntxt = document.getElementsByClassName('expandable')[0].innerText;
console.log(inntxt);
0stone0
  • 34,288
  • 4
  • 39
  • 64
-1

Not sure about what you're trying to achieve here, but what you might want to do is change innerText to innerHTML and then the line breaks are preserved.

Unlike innerText, though, innerHTML lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerText retrieves and sets the content of the tag as plain text, whereas innerHTML retrieves and sets the content in HTML format.

Quoted from https://stackoverflow.com/a/19030857/4073621.

Koen
  • 422
  • 3
  • 16