How do I write a CSS related code from Javascript code?

Hello,

How do I write a CSS related code into a Web page from Javascript code?

That is for example if the Javascript code detects certain condition, then I want it to output a certain CSS code into that page. How is this done?

ThanX,

Where is your BR element?

If for example you had one that’s referenced by an id attribute:


<br id="specialBreak">

You could obtain a reference to that HTML element:


var br = document.getElementById('specialBreak');

and then apply a class name to it.

If instead you are creating the element from within the script itself:


var br = document.createElement('br');

You could then apply the class name to it, before you attach the element to some part of your page.

If instead you’re wanting to edit the stylesheet for the web page, that gets complicated. This page gives some details on the troubles that you’ll face.

http://www.quirksmode.org/dom/changess.html

Hi PMW,

Sorry, but I guess I dont get quite what you mean.
That is I added this 2 code:

<style type="text/css">

br.fancy {
    display: block;
    margin-bottom: 7px;
}

</style>
<script language="JavaScript">

var isIE = window.ActiveXObject ? 1 : 0;

if (isIE == 1)
  {
  // code for IE6, IE5
  br.classname = 'fancy';

  } 

</script>

ThanX,

P.S., Sorry to hear about the earth quake in NZ, I hope did not affect you.

In cases like these it’s better to set a class name on the element, so that the styling and presentation can be kept in a css file.


br.fancy {
    display: block;
    margin-bottom: 7px;
}

The script could then set the class name on some br element like this:


br.classname = 'fancy';

without any further details I assume you mean something along these lines.

 
if(myVar == someValue) {
      document.getElementById('myID').style.color = 'red';
}

Hi,

The CSS code that I need to set is not as simple as the color for a div.
But I need to write multiple lines of CSS for that Web page based on the conditions of the Javascript code being met.

To be exact for example I need to change the br for that Web page to be:

br {display:block;margin-bottom:7px;}

It sounds like then that you want to edit the stylesheet for the page.

The page at http://www.quirksmode.org/dom/changess.html shows you how to do that. It can be tricky to do though, so careful attention to it should ensure a minimum of issues.

Hi,

This does not make sense.
FYI:
1- These pages are dynamically generated for our Social networking service, the Blog part, here:
http://RealNewsPost.com?n=think.41143

So a page can have a few or 100s of BR in it.

2- All I want to do is to set the value of BR to be:

br {display: block; margin-bottom: 7px;}

If the browser is IE. And not otherwise.

Damn IE again :frowning:

Regards,