Home > Net >  Combine string and element and insert it in innerHtml
Combine string and element and insert it in innerHtml

Time:01-19

Imagine I have some element

<p>Hello</p>

user click between e and l letter (put caret in this place) , on this click I want insert some element between those letters . It will be

<p>He<b>Here</b>llo</p>

is there any way to make it ?

Code example:

  const selection = document.getSelection();
  const parent = selection.baseNode.parentNode;
  const b = document.createElement('b')
  b.innerHTML = 'Here'

  parent.innerHTML = 'he'  b   'llo'

It will not work as you understand , I need solution for this case. Caret position I can determine

selection.focusOffset

and this mean that I have to get selection text , and insert on caret position <b>Here</b> element. I've also tried to find method to convert element to string , but haven't foudn . I mean document.createElement(tagName) make it as string , then I can insert it in text

CodePudding user response:

You can use the insertNode method of a Range in the Selection to do it.

Here's a basic example:

const p = document.querySelector('p')
p.addEventListener('click', () => {
  const selection = document.getSelection();
  if(!selection.isCollapsed || !selection.containsNode(p, true))
    return
  const b = document.createElement('b')
  b.innerText = 'here'
  selection.getRangeAt(0).insertNode(b)
})
<p>Some text</p>

CodePudding user response:

      const selection = document.getSelection();
      const text = selection.anchorNode.data;
      const parent = selection.baseNode.parentNode;
      const position = selection.focusOffset;

          const html = [
            text.slice(0, position),
            createdElementSpan.outerHTML,
            text.slice(position),
          ].join('');

          parent.innerHTML = html;

Seems like it works, outerHTML property return string . But also have to find out how to put cursor in correct position

  •  Tags:  
  • Related