views:

2332

answers:

3

how can i change the css attribute value at runtime like all h1 color="blue" and all p color="green". if anyone know it please help me!

+2  A: 

Pretty easy (I'm assuming you want to do this server side)- declare the heading as runat=server and give it an id:

<h1 runat="server" id="someHeading">Blah</h1>

Then you can programmatically manipulate it in the code behind like so:

someHeading.Style.Add("color", "blue");

This will render the following HTML:

<h1 id="someHeading" style="color:blue;">Blah</h1>

You might want do this different and define the styles in a stylesheet and change the class dynamically at runtime.

Update- as you are changing it dynamically, the following might be more appropriate:

someHeading.Style["color"] = "red";

I'm sure someone else will post an answer with how to do it client side. :-)

Another (perhaps better) option to look into server side is using skins and themes. Read the ASP.NET FAQ on these to find out more.

RichardOD
+1  A: 

In JQuery you could simply use

$('h1').css("color","blue");

The ASP.Net codebehind does not have selector to apply css to multiple html tags because the HTML is only generated once most of the code is executed. This happens in the Page_PreRender event.

What you could do is get the rendered html and perform some searches and or modifications wether it be using regular expressions or plain search replaces.

I would advise you to do this using javascript though as modifying the rendered html in the Page_PreRender event is something that will definitely cause you problems later on and is basically not done.

Peter
If you are doing it to multiple controls on the server it would be easy to do it by dynamically changing the skin/theme.
RichardOD
A: 

I beleive he means to every item on the page. I would recommend adding a literal into the header just after your current stylesheets, then add an inline style with the following code:

<asp:Literal ID="litInlineStyles" runat="server" EnableViewState="false" Visible="false">
  <style type="text/css">
  h1 
  {
    color: {h1Colour}
  }
  p
  {
    color: {pColour}
  }
  </style>
</asp:Literal>

I've deliberately disabled the viewstate and visbility so you have to declare each time the page loads what to replace {h1Colour} with and {pColour} as well as setting the literal to be visible.

That should help point you in the right direction.

John_
I should note this is ideally suited to a single page only fix, if you are doing something globally I would probably use themes.
John_