Remove a CSS class from HTML element in the code behind file

How to remove ONE CSS class from a control using .NET

If a control has several classes you can remove one of those classes by editing the class string. Both of these methods require assigning an ID to the HTML element so that you can target it in the code behind.

<asp:Panel ID="mydiv" CssClass="forceHeight class2 class3" runat="server" />

VB.NET

mydiv.CssClass = mydiv.CssClass.Replace("forceHeight", "").Trim()

C#

mydiv.CssClass = mydiv.CssClass.Replace("forceHeight", "").Trim();

OR using html generic control

<div id="mydiv" class="forceHeight class2 class3" runat="server" />

VB.NET

mydiv.Attributes("class") = mydiv.Attributes("class").Replace("forceHeight", "").Trim()

C#

mydiv.Attributes["class"] = mydiv.Attributes["class"].Replace("forceHeight", "").Trim();

Optional Trim to remove trailing white space.


How to remove ALL CSS classes from a control using .NET

VB.NET

mydiv.Attributes.Remove("class")

C#

mydiv.Attributes.Remove("class");

Me.mydiv.Attributes.Remove("class")

is much better since it won't leave a stub behind. It'll produce a cleaner HTML tag.

<div id="mydiv"></div>

If you use this,

Me.mydiv.Attributes("class") = ""

it will produce this instead

<div id="mydiv" class=""></div> OR <div id="mydiv" class></div>


This will remove all CSS classes from the div with ID="mydiv"

Me.mydiv.Attributes("class") = ""

Tags:

Vb.Net

Asp.Net