6

I'm trying to add bold text to my website using javascript, but it literly shows the "<b>". How do i fix this?

var TextBox = document.getElementById("TextBox");

TextData.textContent = "<b> hello </b>"

I tried using the document.write(""); , but it changes the whole website. Any Suggestions?

4
  • You can use css and then add it to the element with jquery...
    – EugenSunic
    Sep 11, 2015 at 20:27
  • 1
    I need to add it with javascript.
    – nachshon f
    Sep 11, 2015 at 20:28
  • Why can't you use CSS for this? Using #TextBox::first-word {font-weight:bold} would surely do it for you?
    – jaunt
    Sep 11, 2015 at 20:33
  • @jaunt Probably some generated CSS. Sep 11, 2015 at 20:38

3 Answers 3

15

You can add first the content to textbox like this:

TextBox.innerHTML = "Hello";

then add its style like this:

TextBox.style.fontWeight = 'bold';

Or you can do it setting the innerHTML property of the element, just like this:

 TextBox.innerHTML = "<b>Hello</b>";

I tend to set style separately. You should avoid adding style like this, better use css classes.

0
5
TextBox.innerHTML = "<b> hello </b>"
1
  • Surprisingly, the tag's surrounding spaces did matter inside innerHTML's string. Is it required by the standard, or could it be a browser-specific issue? Sep 1, 2021 at 6:52
2

Toggle/add a css class on the containing element (TextBox).

document.getElementById('TextBox').className = 'bold';
.bold {
    font-weight: bold;
}
<div id='TextBox'>
    My text.
</div>

Or something like that.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.