Set ASP Literal text with Javascript Set ASP Literal text with Javascript asp.net asp.net

Set ASP Literal text with Javascript


<asp:Literal> controls don't create their own HTML tag.
Therefore, there is no element that you can manipulate.

Instead, you can wrap the <asp:Literal> in a <div> tag with an ID.


An ASP.NET Literal doesn't add any markup to the page. Therefore you have to wrap your content in some container so that you can edit it via JavaScript:

Assuming you had the following Literal on the page:

<asp:Literal runat="server" Id="literalControl" />

And were setting the text via code behind (because if you're not, you could just create the span/div in the markup to begin with and not have this issue):

literalControl.Text = "Some text you want to change";

The code behind becomes:

literalControl.Text = "<span id='myId'>Some text you want to change</span>";

And the JavaScript would be:

document.getElementById('myId').innerHTML = 'New Text';


Wrap the <asp:literal> control in a <div> and then use jQuery if needed to clear the contents like shown below:

<div id="divMyText">  <asp:Literal ID="MyText" runat="server"></asp:Literal></div>

Here is how to clear the text using jQuery:

//Clear the html inside of the div$("#divMyText").html("");