Home > Enterprise >  how to get new lines by copying html as text in another div
how to get new lines by copying html as text in another div

Time:09-27

pls place cursor at the and of lorem ipsum
then hit Enter - new line
then write - dolor
result in divb is - <div>lorem ipsum</div><div>dolor</div>
how to get the following in divb:

<div>lorem ipsum</div>
<div>dolor</div>  

$('#diva').on('input', function(){
  let a = $(this).html();
  $('#divb').text(a);
});
#diva, #divb{background:#ddd; padding:9px;}
#divb{white-space:pre-wrap;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='diva' contenteditable>
<div>lorem ipsum</div>
</div>
<br>
<div id='divb'></div>

CodePudding user response:

Each line in a contenteditable is wrapped in a div.

You can split the HTML by a closing div tag, then join back with a newline:

$('#diva').on('input', function() {
  let a = $(this).html();
  $('#divb').text(a.split("</div>").join("</div>\n"));
});
#diva,
#divb {
  background: #ddd;
  padding: 9px;
}

#divb {
  white-space: pre-wrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='diva' contenteditable><div>lorem ipsum</div></div>
<br>
<div id='divb'></div>

  • Related