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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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")
Method 2
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"
Method 3
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";
Method 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)
Method 5
controlName.CssClass="CSS Class Name";
working example follows below
txtBank.CssClass = "csError";
Method 6
Syntax:
controlName.CssClass="CSS Class Name";
Example:
txtBank.CssClass = "csError";
Method 7
If you want to retain the existing class, this would work:
string existingClass = classMe.Attributes["class"]; classMe.CssClass = existingClass + " some-class";
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0