Add linebreak to textContent or innerText only - in Chrome
Solution 1
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!
Solution 2
This is because textContent
is not aware of style. As a result, e.g., it displays hidden content.
Change c1.textContent
to c1.innerText
and it will display the line break.
cronoklee
Updated on July 09, 2022Comments
-
cronoklee almost 2 years
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>
-
cronoklee about 12 yearsThanks Dennis but now I have the opposite problem, that line breaks that already exist in the content are ignored. Is there any way to get consistency here? (see update above)
-
Dennis about 12 yearsThis is how it's supposed to work. A line break in a HTML page does not get displayed. Use
<br />
instead.