I am trying to make a text editor in JavaScript and it has various features like bolding the text and italics and some others. When the user clicks on any one of them, then anything that they have selected will become edited accordingly. Now I am able to get the selected text and even put strong tags before and after the text but when I do it the text doesn’t get bold only the tags are seen. How can make the text bold? I sorry but I am unable to provide code since its too much and too messy. Thanks for reading query! Also if you know any JavaScript library which could help me solve this problem then you can suggest me.
document.getElementById("button").addEventListener("click", () => { let text = document.getElementById("text").innerText let selection = window.getSelection(); let boldText = "<strong>" + selection + "</strong>" document.getElementById("text").innerText = text.replace(selection, boldText) })
<div id="text"> The dog barks and runs around. </div> <button id="button">Make selected text bold</button>
I am using inner text instead of inner html in order to reproduce the problem
Advertisement
Answer
You are using innerText
to replace which is wrong as we want to change html so use innerHTML
.
Code:
document.getElementById("button").addEventListener("click", () => { let text = document.getElementById("text").innerText let selection = window.getSelection(); let boldText = "<b>" + selection + "</b>" document.getElementById("text").innerHTML = text.replace(selection, boldText) //use innerhtml instead of innertext })
<div id="text"> The dog barks and runs around. </div> <button id="button">Make selected text bold</button>