Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
Combine string and element and insert it in innerHtml

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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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'
  const range = selection.getRangeAt(0)
  range.insertNode(b)
  range.collapse() //unselect inserted text
})
<p>Some text</p>

about 4 years ago · Juan Pablo Isaza Relatório

0

      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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda