logan
logan

Reputation: 8366

Javascript innerHTML ignores Text Format

I have following value in table cell with bold & colour formatting

cell id="total"; value="HI"

But when i change the value of the cell as below, it ignores text formatting

document.getElementById("total").innerHTML = "Hello"

and resulting in

Hello (with out bold and color)

Upvotes: 1

Views: 7176

Answers (3)

webd3sign
webd3sign

Reputation: 21

Yes the best approach would probably be to use CSS styles.

Upvotes: 0

Kevin Ji
Kevin Ji

Reputation: 10499

I think the better solution would be to apply your styles through a stylesheet, as follows:

#total {
    font-weight: bold;
    color: #FF0000; /* Replace this with the right color */
}

Now,

document.getElementById("total").innerHTML = "Hello";

should allow the cell to keep its styles.

Upvotes: 1

Jon
Jon

Reputation: 437834

That's because you are replacing the existing content with just "Hello" -- the styling of the previous content was due to properties of the content itself, and that doesn't stick around because that content is wiped out.

If you want styling for your new content you need to provide it manually, for example

document.getElementById("total").innerHTML = "<strong>Hello</strong>";

Upvotes: 5

Related Questions