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