Reputation: 1623
I tried using the server-side .CssClass
, but this isn't available for me to use.
My div has runat="server"
so I can access it, but I just cannot see .CssClass
in the drop-down when i hit ".". Does anyone know how to get past this or any other solution that might work?
Ok, my bad. I just found out that this does not work for HTML controls, only for asp controls
Upvotes: 4
Views: 36095
Reputation: 422
A better approach to handle adding or removing class for any HtmlGenericControl would be to use the extension as provided below:
public static void RemoveCssClass(this HtmlGenericControl controlInstance, string css)
{
var strCssClass = controlInstance.Attributes["class"];
controlInstance.Attributes["class"] = string.Join(" ", strCssClass.Split(' ').Where(x => x != css).ToArray());
}
public static HtmlGenericControl AddCssClass(this HtmlGenericControl controlInstance, string css)
{
var strCssClass = controlInstance.Attributes["class"];
controlInstance.Attributes["class"] = String.Join(" ", strCssClass.Split(' ').Where(x => x != css).Append(css).ToArray());
return controlInstance;
}
For WebControl the same code can be modified as below:
public static void RemoveCssClass(this WebControl controlInstance, string css)
{
controlInstance.CssClass = string.Join(" ", controlInstance.CssClass.Split(' ').Where(x => x != css).ToArray());
}
public static void AddCssClass(this WebControl controlInstance, string css)
{
controlInstance.CssClass = String.Join($" ", controlInstance.CssClass.Split(' ').Where(x => x != css).Append(css).ToArray());
}
Upvotes: 1
Reputation: 3610
This would be more specific:
HTML
<div id="Test" runat="server"></div>
Server code:
Test.Attributes.Remove("class");
Upvotes: 2
Reputation: 552
This is the same solution as Tim, but I removed the not needed toString method.
myDiv.Attributes.Add("class", myDiv.Attributes["class"].Replace("spacerDiv", ""));
To add a class to a div is somewhat the same.
myDiv.Attributes.Add("class", "spacerDiv");
Upvotes: 0
Reputation: 20374
If you are wanting to read the class name, you will need to use the code:
string className = Test.Attributes["class"].ToString();
If you are wanting to replace a specific class you will need to use the code:
Test.Attributes.Add("class", Test.Attributes["class"].ToString().Replace("spacerDiv", ""));
Upvotes: 18
Reputation: 14470
HTML
<div id="Test" runat="server"></div>
Code Behind
add => Test.Attributes.Add("class", "myClass")
remove => Test.Attributes.("class") = "";
Upvotes: 7