Edgar Navasardyan Edgar Navasardyan -4 years ago 106
HTML Question

Clearing out contenteditable divs from '</br>'

I have a

contenteditable
element in HTML. And I found no post in Internet related to the problem of clearing out div content from html tags like
<div>
and
</br>
that are inserted as a result of user pressing Enter (new line).

In other words, if the user presses Enter, user input is posted to the database with extra html tags.

What is the cleanest solution to this issue?

I am sorry if the question is duplicated, but I failed to found exactly this issue described elsewhere



$(function() {
$('button').click(function() {
alert($('#test').html());
});
});

#test {
line-height: 1.14;
border: solid;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='test' contenteditable='true'></div>
<button>Show me div input</button>




Answer Source

The .html() method returns the line breaks as <br> elements.

You could use the .text() method instead. However, it will remove the line breaks altogether.

If you want to maintain the line breaks, use the innerText property:

$(function() {
  $('button').click(function() {
    alert($('#test').prop('innerText'));
  });
});
#test {
  line-height: 1.14;
  border: solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='test' contenteditable='true'></div>
<button>Show me div input</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download