Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Doctor Q

Administrator
Original poster
Staff member
Sep 19, 2002
40,393
9,184
Los Angeles
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?
 
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!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.