简体   繁体   中英

how to remove a class name from entire page asp.net c#

My codes is like

<th runat="server" id="thTodayToTenTotal" class="redRow">  
<th runat="server" id="thTodayToTenTotal" class="redRow">

I remove the attribute class="redRow" like that from CodeBehind

thTodayToTenTotal.Attributes.Remove("class"); 

It is OK.

But the class "redRow" can have many in my page. How to remove this class name from entire page one time. Then I want to add this class to one html element.I means that I have

<th runat="server" id="wantToAddClass"> 

I add the class from CodeBehind like that

wantToAddClass.Attributes.Add("class", "redRow");

You could achieve that with jQuery, which would be:

$(document).ready (function ({
     var elements = $(".redRow");
     $.each (elements, function(index) {
          elements[index].removeAttr("class");
     });
});

Then problem, unless from a server side control where you can anchor to the event, you wouldn't know which element to remove. Since an id is one per page. Otherwise you'd be trying to parse an html page, Javascript is more than likely ideal.

As CRise commented, you have to loop all web controls and find each control which has class you wanted.

Let me give you some help here.

Lets Create one Utility method.

IEnumerable<Control> FindControl( Control c, Func<Control,bool> predicate )
{
    if( predicate( c ) )
        yield return c;

    foreach (var child in c.Controls) {
        if (predicate((Control)child)) {
           yield return (Control)child;
        }
    }

    foreach( var child in c.Controls )
        foreach( var match in FindControl( (Control)child, predicate ) )
           yield return match;
}

And then call these method wherever you want to check for your class.

foreach(WebControl c in FindControl( Page, c => (c is WebControl) && 
                       ((WebControl)c).CssClass == "redRow" ))
{
     //Do your operation.
}

for further details there are lots of questions already asked in SO. see.

How to select an element by Class instead of ID in ASP.NET?

remove css class in code behind

You can use JavaScript or Jquery too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM