javascript - style not recognized when placed in the head tag -


the following code works if remove style h1 head tag , use inline style shown in commented line, not work listed below.

<!doctype html> <html>     <head>         <style>             h1 {                 text-align: center;                  color: black;             }         </style>         <script>             function changecolor()             {                 var dom = document.getelementbyid("head1");                  var clr = dom.style.color;                 switch(clr)                 {                     case 'black':                         dom.style.color = "red";                         break;                     case 'red':                         dom.style.color = "black";                         break;                 }             }         </script>     </head>     <body onclick="changecolor()">         <!-- <h1 id="head1" style="text-align: center; color: black;">click on me!</h1> -->         <h1 id="head1">click on me!</h1>     </body> </html> 

your appreciated.

if want read style off element comes stylesheet, have use computed style can obtain window.getcomputedstyle().

styles applied via stylesheeets not readable via elem.style. shows styles directly applied specific element (not inherited stylesheets or parents).

you change code , work style sheet values in addition directly applied values:

        function changecolor()         {             var dom = document.getelementbyid("head1");              var clr = getcomputedstyle(dom, null).getpropertyvalue("color");             switch(clr)             {                 case 'black':                     dom.style.color = "red";                     break;                 case 'red':                     dom.style.color = "black";                     break;             }         } 

note: getcomputedstyle() requires ie9 or higher. ie8 , earlier had different way of doing same thing when supporting older versions of ie, polyfill of sort such shown here necessary.


fyi, particular objective here, better design pattern toggle class on/off on element , leave styling the css based on whether class name present or not , not put specific style parameters in javascript.


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -