Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent non-breaking spaces from being created in a contenteditable element?

I have a contenteditable div, which creates many non-breaking spaces when words are deleted or added. This is the format of my code:

<div id="div" contenteditable="true">
    <span>Hello</span>
    <span></span>
</div>

I've tried replacing non-breaking spaces on input:

document.getElementById("div").oninput = function() {
     document.getElementById("div").innerHTML.replace("&nbsp;","");
}

But this doesn't work. Any ideas?

like image 582
Cloud9c Avatar asked Nov 18 '25 04:11

Cloud9c


1 Answers

Another solution without any JavaScript at all: just add white-space: pre-wrap; or white-space: break-spaces; to the styles of your content editable element... and voilà, no more &nbsp; :)

like image 155
Jon Garbayo Avatar answered Nov 19 '25 16:11

Jon Garbayo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!