Sethu Bala
Sethu Bala

Reputation: 457

Convert string to HTML in JavaScript

I have a string being sent to my JavaScript function from my C# code which has a text like:

 Hi <b>Welcome to C#<sup>5.0</sup></b>

I'm populating a div with this string. I need this html content to be rendered in the screen with the bold and superscript applied as below

Hi Welcome to C#5.0

I tried the below it just displays the HTML tags as plain text

myfunction = function(data) {
  var mytext = '<div>'+ data +'</div>;
  $('#mydivid').after(mytext);
}

Is there any other solution neither like the one given here nor like this ?

Note: I cannot declare the string in a hidden variable in my .cshtml file within @HTML.Raw and again use it in my JavaScript.

I have tried using $.parseHTML but I got an error saying

$.parseHTML is not a function

Any solution other than the above solutions are welcome. Thanks in advance.

Upvotes: 0

Views: 568

Answers (3)

selvakumar
selvakumar

Reputation: 654

seems like nothing is wrong with your code. Check if some css is overriding the basic em and sup functionality.

for Example the default style of em is font-style: italic which chould be override by your css

Upvotes: 3

Miguel Coder
Miguel Coder

Reputation: 1954

You listed JQuery in your tags so I figured this would help.

html = $.parseHTML(  'Hi <b>Welcome to C#<sup>5.0</sup></b>' );

Check out this JSFiddle

You can also do this if you want a javascript oneliner.

document.getElementById("mydivid").innerHTML="Hi <b>Welcome to C#<sup>5.0</sup></b>";

Upvotes: 1

Komal
Komal

Reputation: 2736

Try like this

myfunction = function(data) {
  $('#mydivid').html('<div>' + data + '</div>');
}

Upvotes: 2

Related Questions