0

I need to get the text value inside of a div. You can think of it like a text area, where you can do like this:

let inputArea = document.getElementById("text-area");
let text = inputArea.value;

text
// Expected result:
// Hello
//
// Hello
//
// Hello
//
// Hello

Unfortunately, I don't have a text area and I can't do that. So what here's what I did:

(1) Get the HTML node where I need to extract the text (var bodyHtml..)

(2) Convert the HTML node to string (calling extractStringFromNode()..)

(3) Extract the string out of the returned string (calling extractContentFromString()..)

My problem is that I lose the "text formatting". The let text (code above) contains the value of the inputArea with the proper formatting. I lose this when I try to reproduce it using my implementation (code below).

What is the right way to solve this?


var OriginalText;

function parseText(event) {
                // get text
                var bodyHtml = event.composeView.getBodyElement();
                var stringBodyHtml = extractStringFromNode(bodyHtml);
                console.log(stringBodyHtml)
                var text = extractContentFromString(stringBodyHtml);
                OriginalText = text;
                console.log(text);

                // now parse it 
                format(text);
            }


// extract text from html
        function extractContentFromString(s) {
            var span = document.createElement('span');
            span.innerHTML = s;
            return span.textContent || span.innerText;
        };

        // from html node to string

        function extractStringFromNode ( node ) {
            var tmpNode = document.createElement( "div" );
            tmpNode.appendChild( node.cloneNode( true ) );
            var str = tmpNode.innerHTML;
            tmpNode = node = null; // prevent memory leaks in IE
            return str;
        }

        // Expected result: HelloHelloHelloHello
leonardofed
  • 936
  • 2
  • 9
  • 24

1 Answers1

0

Use the CSS property white-space and set it to pre. This will preserve line breaks, however, you must place it in every place you want to have the text with similar spacing.

let div = document.querySelector("div"); 
//this div has CSS styling white-space: pre

span = document.body.appendChild( document.createElement("span") );
//this span does not

span.textContent = div.textContent;
//div will be "formatted" with line breaks. Span will not.
div { 
white-space: pre;
}
<div>This
Is
A
Demo
</div>
<hr/>
zfrisch
  • 8,474
  • 1
  • 22
  • 34