Monday, December 25, 2023

How to hide HTML elements in text only (Lynx) or JavaScript disabled browsers

The general approach would be to show a no-JavaScript version of a page to everyone and then insert HTML tags via JavaScript in browsers that do support it. Now, I prefer to keep my JS code clean and not mix it too much with HTML, especially for this infrequent purpose. So, I am using the following (in HTML file):

<!-- This template holder div is shown to everyone, but it's empty -->
<div id="template-holder"></div>

<!-- This template is parsed only by browsers with JS support -->
<script id="template" type="text/html">

<!-- This is the div you want to hide from browsers without JS support -->
<div id="hide-me">...</div>

</script>

<!-- Use JS (where available) to insert the template into the template holder -->
<script>
document.getElementById("template-holder").innerHTML =
document.getElementById("template").innerHTML;
</script>
<!-- We're done! -->

This way all HTML code stayed in the original file, and we kept our original JS code intact.