Search code examples
javascripthtmlckeditor

Insert HTML tag for selected text inside paragraph tag


I am trying to add new element for selected element in paragraph tag. HTML code snippet as below:

 <div class="parent-bodytext">
     <p>Hello</p>
     <p>This one is</p>
     <p>Sample Text</p>
 </div>

So in above snippet I have selected "one" word from second P tag and using any event I am trying to add element to that selected text so that output will be like below:

 <div class="parent-bodytext">
     <p>Hello</p>
     <p>This <strong>one</strong> is</p>
     <p>Sample Text</p>
 </div>

So How can add this newly created "Strong" element for selected the selected text?


Solution

  • You may want to use window.getSelection for this purpose

    const wrapper = document.getElementsByClassName('parent-bodytext')[0];
    
    wrapper.addEventListener('mouseout', event => {
       const selection = window.getSelection();
       if (selection.rangeCount) {
           const replacement = document.createElement('strong');
           replacement.textContent = selection.toString();
           const range = selection.getRangeAt(0);
           range.deleteContents();
           range.insertNode(replacement);
       }
    });
     <div class="parent-bodytext">
     <p>Hello</p>
     <p>This one is</p>
     <p>Sample Text</p>
     </div>