Named style property can't be seen

Discussion in 'Web Design and Development' started by Doctor Q, Jul 25, 2006.

  1. Doctor Q Administrator

    Doctor Q

    Staff Member

    Joined:
    Sep 19, 2002
    Location:
    Los Angeles
    #1
    I'm puzzled about a quirk in a web page I'm working on. See how puzzled I am? --> :confused:

    Here is a snippet of the page:
    Code:
    <html>
    <head>
    <script type="text/javascript">
    ...document.getElementById('myid').style.display...
    </script>
    </head>
    <body>
    <div id="myid" style="display:block">hello</div>
    </body>
    </html>
    When the Javascript is executed (in an onclick() action), the expression
    Code:
    document.getElementById('myid').style.display
    comes out with the value "block", which is the value I expect.

    So far so good.

    However, if I change the page to the following, using named styles instead of anonymous inline classes, then the expression comes out null instead of "block". That's what puzzles me.
    Code:
    <html>
    <head>
    <style>
    .myclass { display: block }
    </style>
    <script type="text/javascript">
    ...document.getElementById('myid').style.display...
    </script>
    </head>
    <body>
    <div id="myid" class="myclass">hello</div>
    </body>
    </html>
    By the way, If I change "display:block" to "display:none" in either example, it causes the word "hello" to disappear, so I know my style is in effect. I just can't "see" the "display" setting in the Javascript.

    I have the same problem in Safari or in Firefox.

    Can somebody explain to me the principle that I'm missing?
     
  2. Palad1 macrumors 6502a

    Palad1

    Joined:
    Feb 24, 2004
    Location:
    London, UK
    #2
    element.style.property can only be used agains css properties defined inline as in :
    PHP:
    <elem style="property:val" />
    and doesn't map to properties defined via a css rule as in
    PHP:
    <style>.myClass{property:val}</style>
    <
    elem class ="myClass" />
    I'm sorry, but you'll either have to switch to inline styles or create alternate css classes
    PHP:
    <style>
    .
    myClass{color:red;} 
    .
    myClassAlt{color:blue;}
    </
    style>

    <
    script>
    function 
    toggle()
    {
     
    vart elem=document.getElementById('myID');
     if(!
    elem){alert('not found!')}
     
    elem.className=(elem.className ="myClass"?"myClassAlt":"myClass");
    }
    </script>

    <elem ID="myID" onMouseOver="toggle()" onMouseOut="toggle()" class="myClass">hello</elem>
    Watch out, changing classnames can trigger a reflow in the layout and slow the page rendering

    Good luck!
     
  3. Doctor Q thread starter Administrator

    Doctor Q

    Staff Member

    Joined:
    Sep 19, 2002
    Location:
    Los Angeles
    #3

Share This Page