I want to create a simple CSS-based language switcher.
Consider a single static HTML page with content in, say, 3 languages:
<h1 lang="en">Hello World</h1>
<h2 lang="de">Hallo Welt</h1>
<h2 lang="fr">Bonjour la Mond</h1>
...
<p lang="en">This is my english webpage...</p>
<p lang="de">Dies ist meine deutsche Webseite...</p>
<p lang="fr">Je ne parles pas francais</p>
When the page loads, we want to detect the user’s language (navigator.language || navigator.userLanguage
) and display only :lang(en)
elements hiding all german or french sections.
*[lang=en] {display:block}
*[lang=de] {display:none}
*[lang=fr] {display:none}
Now, if the user selects German, we want some JavaScript to switch the stylesheet out globally (not by element) so that we override the above CSS with:
*[lang=en] {display:none}
*[lang=de] {display:block}
*[lang=fr] {display:none}
How can one achieve such a CSS override globally in JavaScript?
Notes:
- I don’t want to select HTML elements and toggle their display – I want to overwrite the global CSS.
- How the language is selected is irelevant – it will be an
onclick
oronchange
event which triggers the JS - I don’t mind having all
lang
elements display as block though it would be interesting how to toggle their display property betweennone
and<original>
without losing saydisplay:inline
.
2
Answers
I can only say this is a costly idea but basically doable
One way which I can think of achieving this is to create separate stylesheets for languages and then programmatically switch between them.
display:block
to*[lang=de] {display: block}
to german.css and othersnone
and so on)Id
to it.setAttribute
is the key.CODE DEMO