Programmatically remove a specific class name from an HTML element

In C # ASP.NET, I add a class to <input> using:

 myInput.Attributes.Add("class","myClass"); 

At some point, I would like to remove the added class (not all classes). Is there a row equivalent:

 myInput.Attributes.Remove("class","myClass"); 

.Remove() seems to accept only the key (no pair value). Thanks!

+4
source share
2 answers

There is nothing inherent to manage multiple values ​​in an attribute.

You will have to parse the list, remove the class name and update the attribute.

Something like (untested):

 var classes = myInput.Attributes["class"].Split(' '); var updated = classes.Where(x => x != "classtoremove").ToArray(); myInput.Attributes["class"] = string.Join(" ", updated); 
+10
source

I got inspiration from the Odeds post and created these two extension methods that you should develop:

 public static void AddCssClass(this WebControl control, params string[] args) { List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>(); List<string> classesToAdd = args.Where(x => !classes.Contains(x)).ToList<string>(); classes.AddRange(classesToAdd); control.CssClass = String.Join(" ", classes); } public static void RemoveCssClass(this WebControl control, params string[] args) { List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>(); classes = classes.Where(x => !args.Contains(x)).ToList<string>(); control.CssClass = String.Join(" ", classes); } 

Methods are simply used to add or remove CSS classes from WebControls (from where Button s, Label s, Panel , etc. everything inherits), for example myButton.AddCssClass("class1", "class2"); or myButton.RemoveCssClass("class2"); .

This can be very little overhead, but managing the CssClass property can also be a little difficult, as you are forced to handle the spaces on your own.

How many times have you not seen this, for example?

 string myCssClass = "class1"; myButton.CssClass += " " + myCssClass; 

Please feel free to improve the methods! :)

+2
source

Source: https://habr.com/ru/post/1412573/


All Articles