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?
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")
Clear and Remove on the Attributes collection. msdn.microsoft.com/en-US/library/…<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 commentclassMe.Attributes.Add("class", classMe.Attributes["class"] + " some-class" to not overwrite what you already haveAssuming 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";