0

I cannot wrap my head around this. I want to duplicate the text that's just been written and insert it at the cursor point. span.className='newSpan' gets inserted correctly as a span, but then adding span.innerHTML=content afterwards removes the span. Other combinations have resulted in a "Failed to execute 'insertNode' on 'Range': parameter 1 is not of type 'Node'" error.

if (e.keyCode == 32) {
            var cursor = document.getSelection().getRangeAt(0);
            var content = document.getSelection().anchorNode.data
            var span = document.createElement("span")
            span.className = 'newSpan'
            // and what I'd basically like to do:
            span.innerHTML = content
            cursor.insertNode(span)

Attempting to do something like $('.newSpan').text(content) afterwards also doesn't work.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
MikeyB
  • 460
  • 1
  • 6
  • 22
  • Please add the relevant HTML and complete JavaScript so that we can execute your code and replicate your issue as well as provide you with a working answer. – Scott Marcus Jan 23 '18 at 23:20
  • inner HTML includes the span container... of course overwriting it would remove the tag. – Daniel Tate Jan 23 '18 at 23:24
  • obviously innerHTML would mean the outer HTML was overwritten, obviously. Any attempt at doing jQuery style '.html(content)' has failed on my part. So, is there a way to add text or html to a span in such a way? – MikeyB Jan 23 '18 at 23:28
  • checkout examples from here: https://stackoverflow.com/questions/11076975/insert-text-into-textarea-at-cursor-position-javascript – num8er Jan 23 '18 at 23:33
  • Thanks num8er but I'm getting a 'Cannot set property 'nodeValue' of null' error. Without the line the span gets created, so I don't know what could be 'null'. – MikeyB Jan 23 '18 at 23:36

0 Answers0