vizz29
vizz29

Reputation: 19

I want to make a HTML text editor having bold functionality using window.getSelection

It makes the whole text bold. I want only selected text to get bold (Strictly no exec Command)

let boldBtn = document.getElementById('Bold-Btn');
let boldClickListener = (event) =>
{
    event.preventDefault();
    let selection = window.getSelection();
    let final = `<span class="text-bold">${selection.focusNode.textContent}</span>`;
    selection.anchorNode.parentElement.innerHTML=final;
    console.log(selection);
};

boldBtn.addEventListener('click',boldClickListener);

Upvotes: 0

Views: 1028

Answers (1)

JoshG
JoshG

Reputation: 6745

One way of doing this might be to do the following:

  • Get the window selection.
  • Convert the selection to a string to get the text.
  • Create the element that will be bold.
  • Replace the selected text contained in the innerHTML of the parentElement with the bolded element.

Example based on the code you provided:

let boldBtn = document.getElementById('Bold-Btn');
let boldClickListener = (event) => {
  event.preventDefault();
  // Get selection
  let selection = window.getSelection();
  // Get string of text from selection
  let text = selection.toString();
  // Create bolded element that will replace the selected text
  let final = `<span class="text-bold">${text}</span>`;
  // Replace the selected text with the bolded element
  selection.anchorNode.parentElement.innerHTML = selection.anchorNode.parentElement.innerHTML.replace(text, final);
};

boldBtn.addEventListener('click', boldClickListener);
.text-bold {
  font-weight: bold;
}
<div>
Test this text
</div>
<button id="Bold-Btn">
Bold
</button>

Note that you may want to add some more logic when creating your bold element to handle if any existing text is already bold.

Upvotes: 2

Related Questions