How to hide parts of HTML when JavaScript is disabled?

I had been looking around for a way to do this so that I could hide a navigation dropdown menu that gets rendered nonfunctional when javascript is enabled. However, all of the solutions for changing the display property did not work.

So, what I did first was assigned an ID (ddown) to the div element surrounding the dropdown menu.

Then, within the head section of the HTML document, I added this in:

<noscript>
    <style>
        #ddown {display:none;}
    </style>
</noscript>

And that just worked. No dependency on javascript, jquery, or any other scripting: just pure HTML and CSS.


Default the bits you want to hide as styled as display:none and switch them on with jQuery or JavaScript.


By the way, is it worth the effort nowadays?

Yes, it's worth worrying about accessibility. You should use progressive enhancement where possible, i.e. make a basic version that works without scripting and then add the scripting functionality on top of it.

A simple example would be a pop-up link. You could make one like this:

<a href="javascript:window.open('http://example.com/');">link</a>

However, this link wouldn't work if someone, say, middle-clicked or tried to bookmark it, or had scripts disabled etc. Instead, you could do the same thing like this:

<a href="http://example.com/" 
   onclick="window.open(this.href); return false;">link</a>

It's still not perfect, because you should separate the behavior and structure layers and avoid inline event handlers, but it's better, because it's more accessible and doesn't require scripting.


here's a video tutorial on how this can be done with jQuery: http://screenr.com/ya7

Code:

<body class="noscript">
<script>
$('body').removeClass('noscript');
</script>
</body>

And then just hide the relevant elements under body.noscript accordingly.

edit However, JQuery might be bloated for a small fix like this one, so I suggest Zauber Paracelsus' answer since it does not require JQuery.