Cloud9c
Cloud9c

Reputation: 329

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?

Upvotes: 2

Views: 1929

Answers (3)

Jon Garbayo
Jon Garbayo

Reputation: 105

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; :)

Upvotes: 4

Mohammed Omer
Mohammed Omer

Reputation: 1236

you have used getElementById(), while you are not using any id in your HTML code, beside the above answer mentioned the innerHTML problem

Upvotes: -1

Jack Bashford
Jack Bashford

Reputation: 44135

You need to assign the innerHTML to the changed text like so:

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

Because as shown in this MDN page:

The original string is left unchanged

So you need to assign the result of replace to something.

Upvotes: 2

Related Questions