Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!