简体   繁体   中英

How do I make text bold after the user clicks a button?

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

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>

Here is some code that I used to change to inputted text on a button click

<input type="text" id="sign" value="">
<p style = "font-family: 'Dancing Script', cursive; font-size:50px;" 
id="signOutput"></p>
<button onclick="signFunction()">Output Signature</button>

<script>

function signFunction() {var x = document.getElementById("sign").value;
         document.getElementById("signOutput").innerHTML = x;
         }

</script>
<p id="mypar">Hello</p>
<br>
<button type="button" onclick="changeStyle()">Click Me</button>
<script>
function changeStyle(){
    var element = document.input
    var element = document.getElementById("mypar");
    element.style.fontWeight = "bold";
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM