There are different ways to make text bold in JavaScript. However, an straightforward way is to use the style.fontWeight
property. The fontWeight
property is used to specify how thick or thin the characters of a text should be displayed.
You can simply set the value of the fontWeight
property to ‘bold’ or ‘700’ to make the text bold. The value 700 is same as bold.
Let’s take an example, which has a paragraph and a button inside a div element. We want to make the text of the paragraph bold whenever someone clicks the button:
<div> <p id="textBox">This is some random text which will be bolded by button click.</p> <button id="textBolder">Make Text Bold</button> </div>
To make the text of the paragraph bold, we can set its fontWeight
property to ‘bold’ inside the click event listener which will be fired on the button click.
See the below JS code:
// Get the elements let textBolder = document.getElementById('textBolder'); let textBox = document.getElementById('textBox'); // Fires on button click textBolder.addEventListener('click', function(event){ // Make the text bold textBox.style.fontWeight = 'bold'; });
After running the above code, you will get the following output:
As you can see from the above output, the paragraph’s text become bold as soon as we click the button.
Method 2: Use HTML’s <b> Tag to Bold the Text
You can also use the HTML’s <b>
tag to make the text bold with JavaScript. If you put any text between the <b></b>
tags, it will automatically become bold. We will use this concept to make the text bold.
Let’s consider the previous example and try to make the text bold using the <b>
tag:
// Get the elements let textBolder = document.getElementById('textBolder'); let textBox = document.getElementById('textBox'); // Fires on button click textBolder.addEventListener('click', function(event){ // Get the text let plainText = textBox.innerText; // Make the text bold textBox.innerHTML = '<b>' + plainText + '</b>'; });
Output:
Conclusion
Making a text bold is quite easy with JavaScript. You can either set the fontWeight
property to ‘bold’ or put the element’s text inside the <b></b>
tags using the innerHTML
property.
In both cases, the text of the target element will become bold.
Thanks for reading.