cronoklee cronoklee - 4 months ago 28
HTML Question

Add linebreak to textContent or innerText only - in Chrome

This is a complicated one! Im working with contentEditable in Chrome and I'm experiencing a head melting problem. When I press the return key, Chrome inserts a new div into the innerHTML. This is fine and dandy. The problem is that the line break is nowhere to be found in the div's textContent. I really need to figure out a way to add the line break to the textContent in the same place as the div break in the innerHTML.

Any Ideas?

UPDATE:

I can use innerText but then line breaks that are there when the page loads are ignored. I need consistency across one of these methods. In other words, I need textContent to show newly inputted line breaks or innerText to show line breaks that existed on page load.

Here's an updated demo:



function checkit() {
var c1 = document.getElementById('c1')
alert("TEXTCONTENT:\n" + c1.textContent + "\n\nINNERTEXT:\n" + c1.innerText + "\n\nINNERHTML:\n" + c1.innerHTML)
}

div {padding: 20px; border-bottom: 1px solid #CCC;}

<div><a href="#" onclick="checkit()">check it</a></div>

<div contentEditable="true" id="c1">click inside this <b>div</b>,
press return and then press <b>check it</b> above</div>




Answer

I've solved this by loading a different variable for each situation:

On page load, I use textContent which keeps line breaks intact. When the user starts typing, I use innerText which recognises inserted page breaks. A simple if statement will do the trick!

Comments