0

I am modifying the inner html of a contenteditable to wrap a span around certain text that the user types. This is working great, except every time the user creates a line break, the new line also comes across as a span with the same id and styling as the span they were just typing in.

I have seen prevent contenteditable mode from creating <span> tags but in that case, they are trying to remove all spans (or at least that's what everyone's advising them to do). I however, need the spans that I intentionally create, I just don't want them multiplying.

I'm using Chrome 61 right now, but I need solutions that will not produce problems with Chrome, FireFox, Edge, IE 11, or Safari since I need to support those browsers.

Glen Pierce
  • 4,401
  • 5
  • 31
  • 50
  • What code are you using to wrap the text in spans? Could there be an issue with your code? – S. Walker Oct 14 '17 at 00:56
  • I don't think that could be it. I'm only adding a single span to the inner html. When I read the html, I see the single span before I press enter and see another span with duplicate attributes on the new line. – Glen Pierce Oct 14 '17 at 01:03

1 Answers1

0

I could put a span-killer in the onKeyDown for the enter key like so:

document.addEventListener('keydown', function(event) {
    if(event.keycode == 13) {
        var span = window.getSelection().anchorNode.parentNode;
        if(span.id === "spanThatShouldntAppearAfterPressingEnter"){
            unwrap(span);
        }
    }
}, true);
function unwrap(el){
    var parent = el.parentNode; // get the element's parent node
    while (el.firstChild){
        parent.insertBefore(el.firstChild, el); // move all children out of the element
    }
    parent.removeChild(el); // remove the empty element
}

I don't really want to do that, can anyone think of something more elegant?

Glen Pierce
  • 4,401
  • 5
  • 31
  • 50