67

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, ie on Page_Load. Is it possible?

7 Answers 7

128

If you want to add attributes, including the class, you need to set runat="server" on the tag.

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

Then in the code-behind:

classMe.Attributes.Add("class", "some-class")
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, I was sure it would be this simple.
@Tyler, no. This adds a new class name to the control. You can also use Clear and Remove on the Attributes collection. msdn.microsoft.com/en-US/library/…
I'm not sure if i'm missing something, but if you have a class on the initial div (eg. <div id="classMe" runat="server" class="original"></div>, the original class declaration is wiped out and you're left with just class="some-class" using the code above....seems to contradict @chris-haas's last comment
if you want to preserve existing classes, you need to do something like: classMe.Attributes.Add("class", classMe.Attributes["class"] + " some-class" to not overwrite what you already have
@DevDave This does override existing classes because you are changing the entire class attribute. This is the same as setAttribute in javascript. "Adds a new attribute or changes the value of an existing attribute"
|
17

If you're not using the id for anything other than code-behind reference (since .net mangles the ids), you could use a panel control and reference it in your codebehind:

<asp:panel runat="server" id="classMe"></asp:panel>

classMe.cssClass = "someClass"

Comments

11

Assuming your div has some CSS classes already...

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

The following won't replace existing definitions:

ClassMe.CssClass += " second";

And if you are not sure until the very last moment...

string classes = ClassMe.CssClass;
ClassMe.CssClass += (classes == "") ? "second" : " second";

Comments

4
BtnAdd.CssClass = "BtnCss";

BtnCss should be present in your Css File.

(reference of that Css File name should be added to the aspx if needed)

Comments

4
controlName.CssClass="CSS Class Name";

working example follows below

txtBank.CssClass = "csError";

Comments

2

Syntax:

controlName.CssClass="CSS Class Name";

Example:

txtBank.CssClass = "csError";

Comments

0

If you want to retain the existing class, this would work:

string existingClass = classMe.Attributes["class"];
classMe.CssClass = existingClass + " some-class";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.