Which is best practice for displaying an HTML element that is initially to be hidden?
- Create the element in the HTML and hide it with CSS. When it is time to use it, show it with JavaScript.
- When the element is needed, create and show it with JavaScript.
The downside to the former is that a potentially unnecessary element is in the HTML and must be initially hidden with CSS. The downside to the latter is that HTML is in the JavaScript file.
EDIT: Adding Examples
One example would be adding a loading indicator or displaying a modal window.
There are a lot more factors that go in to this. If you are inserting a small element like a link or select list options, then dynamically generating them in javascript is a non-issue. If you are generating a repeating series of complex HTML, it might be a good idea to create a template of the html in the markup (so that the web designers can maintain it) and then make the template hidden in CSS. Then use javascript (e.g. jQuery) to clone the template and insert it in to the DOM. This gives you the benefit of using more native implementations to extend the DOM tree without all the nasty javascript-that-parses HTML mess.
But ultimately the practicality comes down to this: Who is going to maintain the code? Will the more elegant solution be something that the maintainer will understand? Or will putting everything in javascript (despite its inelegance) be something that a junior coder would be able to expand or update as the need arises in the future?
The vast majority of web browsers run on hardware that is ridiculously over-powered for what the user actually “needs”, at least in terms of web browsing. Because of this, inefficient solutions in Javascript are rarely ever an immediate issue. If you are targeting mobile browsers though, efficiency == battery life. So if you are doing heavy dom-manipulation then consider the suggestion above and see if it works for your case.
Best of luck!
-Brendan