Reputation: 19
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
Reputation: 6745
One way of doing this might be to do the following:
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