9

Possible Duplicate:
How to change/remove CSS classes definitions at runtime?

I have a HTML page which uses external css file .I want to change css rules of external file using javascript at runtime.

myHtml.html

<html>
  <head>
    <link rel="stylesheet" href="myCSS.css" type="text/css">
    <script type="text/ecmascript" src="myJS.js" />
  </head>
  <body>
    <p> change css style color for this element using javascript </p>
  </body>
</html>

myCSS.css

.p{ color:blue}

myJS.js

var ss = document.styleSheets[0]
var firstRule = ss.rules[0] // null

I want to perform the operation :

firstRule.style.color = "red" ;
Community
  • 1
  • 1
radhe001
  • 324
  • 1
  • 3
  • 16

2 Answers2

2

You can override external css properties by using internal css. It could also be achieved in three different ways :

1) declare your css properties in the page itself for example as per your code include "style" tags and write properties in between

< html>

 < head>
   < link rel="stylesheet" href="myCSS.css" type="text/css">
   < script type="text/ecmascript" src="myJS.js" />
   <style type="text/css">
   ........................
   .........................
   </style>
< /head>
< p > change css style color for this element using javascript   
< /p>

< /html>

2) Using inline css

< p style="font-color:red;"> change css style color for this element using javascript   
< /p>

3) Using javascript : It's just another way or you can say indirect way to achieve implement internal css implementation. See first answer given by @Misam

shivshankar
  • 691
  • 2
  • 14
  • 31
0

You can acheive in following manner

var div = document.getElementById("newDiv");
div.style.position = "absolute"; 
div.style.top = "200px"; 
div.style.left = "200px"; 

likewise you can edit/add more css properties See if this helps to alter CSS rules : Alter CSS Rules

Misam
  • 4,320
  • 2
  • 25
  • 43
  • 3
    Sir , I know I can do this but my requirement is something else . I want to know if I can change css rules defined in external style sheet or not . If yes then how ? – radhe001 Jul 16 '12 at 06:46
  • I have posted a link in above answer, see if it helps – Misam Jul 16 '12 at 06:51
  • 2
    Sir ,I've already visited that link .I can change the css rules if it is written inline in the same document but if the style sheet is embedded using link element (as I mentioned in example) then I can not get the css rules defined there .It returns null when I tried document.styleSheets[0].rules – radhe001 Jul 16 '12 at 06:59
  • This is not a solution. I also cannot get the cssRules of embedded external stylesheets. I think it's because CORS. – jscripter Mar 22 '14 at 08:04
  • 1
    Not the solution to the problem specified – Abdul Rab Memon May 07 '18 at 11:50