0

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");

2 Answers2

0

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.

JD Davis
  • 3,517
  • 4
  • 28
  • 61
Greg
  • 11,302
  • 2
  • 48
  • 79
0

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.

Community
  • 1
  • 1
Bharat
  • 5,869
  • 4
  • 38
  • 58
  • If you do this via code behind, it will be incredibly slow. Since every aspect of the page is considered a control. – Greg Dec 21 '16 at 21:29
  • 1
    @Greg: ya, you're right but i have to answer in only C# and code behind, and you have already answered in JQuery, so we can suggest user to use scripting languages but it always depends on requirement.. – Bharat Dec 22 '16 at 04:35
  • I know, just encouraging op not to do it unless he has to, but rethink the solution. – Greg Dec 22 '16 at 05:21