Style set in external style sheet not seen

I remember having had the same problem some time ago, and I thought I had asked here and gotten the answer. But I can’t find the thread and I don’t remember the answer, so I’ll ask again.

I have set the display of a div to none in an external style sheet.

Then I use this function to show and hide the div

function toggle_visibility(id) {

    var e = document.getElementById(id);
    
    if (e.style.display == 'block')
        e.style.display = 'none';
    else
        e.style.display = 'block';
}

It works fine, because I changed the logic of the if. I started by checking if e.style.display was equal to ‘none’, but then I had to click twice to show the div.
I added an alert(e.style.display) to the function, and discovered that the first time the function is called , the value of e.style.display is empty.

Why? Why doesn’t it return the value set in the style sheet? The div is hidden at that moment.

You are testing the value in the style attribute of the tag (not the stylesheet) so unless you set it to none it won’t be there.

e.g.

<div style="display:none" id="test">test</div>

Now it will work because it will find the rule and then the JS changes it to:

 <div style="display:block" id="test">test</div>

In your original version you have to click twice because the first click just does the else part.

  else
        e.style.display = 'none';

Now the tag has a style attribute the routine will work ok on second click.

 <div style="display:none" id="test">test</div>

I generally prefer to add classes to the element and handle it from the stylesheet because you would need to use !important rules in your stylesheet to over-ride that inline style,

Thanks. Yes I prefer to not use inline styles as well.
Ok in my ignorance I assumed that styles set by the style sheet would be applied to the div and therefore be “seen” by JS. But I guess that would’ve been too easy.

So how can I get JS to notice the style set in the style sheet? Or better, how can I get the actually applied style in JS?

I guess I’ll have to look into getComputerStyle and currentStyle ?
Of course a single method for all browsers would have been to easy :frowning:

Why not just use classes?

e.g.

function toggle_visibility(id) {
var e = document.getElementById(id);
e.classList.toggle(‘show’);
}

Then in css:

#test{display:none;}
#test.show{display:block}

classList is IE10+ only (+ other modern browsers of course).

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.