Removing CSS class from <li> tag in ASP.net from code behind

Suggested method

liComPapers.Attributes["class"] = liComPapers.Attributes["class"].Replace("NoDisplay", "");    

will cut another css classes that contains string "NoDisplay" and will cause errors

E.g.

<li class="NoDisplay AnotherClass-NoDisplay"></li>

becomes

<li class=" AnotherClass-"></li>

So, more safely solution would be

liComPapers.Attributes["class"] = String.Join(" ", liComPapers.Attributes["class"]
                                        .Split(' ')
                                        .Where(x => x != "NoDisplay")
                                        .ToArray());

If I understand correctly:

If you wish to remove only NoDisplay, you could replace that part of the string with an empty string:

liComPapers.Attributes["class"] = liComPapers.Attributes["class"].Replace("NoDisplay", "");

However, .Add("class", "NoDisplay") won't add a new class to your class attribute. It will create a new class attribute with the value NoDisplay. Therefore if your markup is currently:

<li class="myClass"></li>

It would become:

<li class="myClass" class="NoDisplay"></li>

This is invalid markup.

To append new classes to an element with existing classes, you can do:

liComPapers.Attributes["class"] += " NoDisplay";

This would then render:

<li class="myClass NoDisplay"></li>

I've just made a sample to test your code, and found that the following part will do exactly what you want:

 var newClassValue = liTest.Attributes["class"].Replace("NoDisplay", "");
 liTest.Attributes["class"] = newClassValue;

Tested and Working: if (for some reason) the above code didn't work, I would recommend another approach, which is similar to the previous, with another way to replace the class value

var newClassValue = liTest.Attributes["class"].Replace("NoDisplay", "");
liTest.Attributes.Remove("class");
liTest.Attributes.Add("class",newClassValue);

liComPapers.Attributes.Remove("class");

we can remove the CSS attribute for the Particular li tag

Tags:

C#

Html

Css

Asp.Net