Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda