Conditionally hiding HTML elements with jQuery/CSS


Say you want an item in a page to be hidden, but visible when Javascript is disabled.

You could use $(".classname").hide(); in a Javascript file, but it will fire before the elements have loaded so won't work.

You could put the above at the bottom of the page, or wrap it in $(document).ready(), but then it will only fire once the page has finished loading so the item will be visible until then.

You could hide the item with CSS by default, then put a style element inside a noscript element (<noscript><style type="text/css">.classname{display:block}</style></noscript>) so the item will be shown only if javascript is disabled. However, this is invalid in XHTML (style elements can only go in the head of the document and noscript elements can only go in the body).

You could use Javascript to add a style element to the head of the page. document.write() doesn't work in XHTML, but this does: $("head").append("<style type='text/css'/>.classname{display:none}</style>. You can't do this from within an external file, as the head element won't yet have been rendered, so you have to add this code in a script element within the head element. Also Safari won't notice that the stylesheet has been added unless you append something to the style element, so...

Here's the best solution so far, run from within the head element:

$("head").append("<style type='text/css'/>").find("style:last").append(".classname{display:none}");

Update: sadly that doesn't work in IE6, as you can't append text to a style element. For now we'll have to use a specific workaround for Safari:

$("head").append("<style type='text/css'>.classname{display:none}</style>"); if ($.browser.safari){ $("head").find("style:last").append(" ") }