0

I am using aspx. If I have HTML as follows:

<div id="classMe"></div>

I am hoping to dynamically add a css class through the code behind file, i.e. on Page_Load. Is it possible?

1
  • Make the div to runat="server". Commented Jun 26, 2014 at 9:09

2 Answers 2

2

If you want to use a control on serverside make it runat=server or even better: use a servercontrol in the first place. In this case you should use a Panel which is rendered as a div:

<asp:Panel ID="PanelID" CssClass="classMe" runat="server"></asp:Panel>

or from codebehind:

protected void Page_Load(object sender, EventArgs e)
{
    PanelID.CssClass = "classMe";
}

But if you want to stay with your div:

<div id="DivID" runat="server"></div>

codebehind:

protected void Page_Load(object sender, EventArgs e)
{
    DivID.Attributes.Add("class", "classMe");
}
Sign up to request clarification or add additional context in comments.

Comments

0

Change the div to something like:

<div id="classMe" runat="server"></div>

Then in your code-behind ASPX.CS file, you can access it.

E.g.

protected void Page_Load(object sender, EventArgs args)
{
    // Access it like this to set a CSS class.
    classMe.Attributes["class"] = "MyCssClass";

    // Access it like this to directly add an inline CSS style:
    classMe.Style.Add("color", "red");
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.